|
|
|
|
|
by jpatte
4123 days ago
|
|
LINQ IEnumerable functions are implemented using the `yield return` operator: public static IEnumerable<T> Where<T>(IEnumerable<T> source,
Predicate<T> predicate)
{
foreach(var item in source)
{
if(predicate(item))
yield return item;
}
}
which means var results = myList
.Where(x => x.name == 'Person');
.Where(x => x.age > 18);
.ToList();
is executed just like var results = new List<Foo>();
foreach(var x in myList)
{
if(x.name == 'Person')
{
if(x.age > 18)
results.Add(x);
}
}
|
|
In fact, how else could "Where" be implemented while keeping lazy semantics?
(Rust, AFAIK, can actually do this, by inlining everything including the lambdas.)