I know Linq is defferedexecution but I want to understand what the compiler does with a statement like this and how it works under the hood
I find Linq fascinating but I worry that I dont understand what is happening under the hood
Where() is an extension method that could be implemented as something like this:
IEnumerable<T> Where(self IEnumerable<T> sequence, Func<T, bool> predicate)
{
foreach(T current in sequence)
if( predicate(current) )
yield return current;
}
x => x == 1 is an anonymous procedure that returns true if x == 1 and false otherwise, something like so:
bool predicate(T value)
{
return value == 1;
}
For the details of how the iterator block in Where() compiles, there's a great series explaining how they are compiled starting here on Eric Lippert's blog.
It's filtering the query to values which are equal to 1. Consider
IEnumerable<int> values = ...;
IEnumerable<int> filteredValues = values.Where(x => x == 1);
Another way to write this would be the following
public static IEnumerable<int> ExampleWhere(IEnumerable<int> values) {
foreach (var x in values) {
if (x == 1) {
yield return 1;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With