Skip to content

Instantly share code, notes, and snippets.

@arialdomartini
Created March 11, 2024 17:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arialdomartini/9053e45766a996ca3ca76631cab23ca1 to your computer and use it in GitHub Desktop.
Save arialdomartini/9053e45766a996ca3ca76631cab23ca1 to your computer and use it in GitHub Desktop.
linq_and_foreach.cs
public class VersionTest
{
private readonly ITestOutputHelper _outp;
public VersionTest(ITestOutputHelper outp)
{
_outp = outp;
}
[Fact]
void enumerable_with_foreach()
{
IEnumerable<int> LinqAndForeach()
{
List<int> strings = new List<int> { 1, 2, 3, 4, 5 };
var resultOfLinq = strings
.Select(i => i * 2)
.Where(i => i > 2)
.Select(i => i == 8 ? throw new Exception() : i); // se li esegue tutti schianta!
foreach (var result in resultOfLinq)
{
_outp.WriteLine($"Executing with {result}!");
yield return result;
}
}
var result = LinqAndForeach().Take(2).ToList();
Assert.Equal(2, result.Count);
}
[Fact]
void enumerable_with_LINQ_only()
{
IEnumerable<int> LinqAndForeach()
{
List<int> strings = new List<int> { 1, 2, 3, 4, 5 };
return
strings
.Select(i => i * 2)
.Where(i => i > 2)
.Select(i => i == 8 ? throw new Exception() : i) // se li esegue tutti schianta!
.Select(result =>
{
_outp.WriteLine($"Executing with {result}!");
return result;
});
}
var result = LinqAndForeach().Take(2).ToList();
Assert.Equal(2, result.Count);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment