Linq.Where (x => x == 1) - What does the compiler do?

I know that Linq is defferedexecution, but I want to understand what the compiler does with this statement and how it works under the hood

I find Link fascinating, but I worry that I don't understand what is happening under the hood.

+4
source share
4 answers

Where () is an extension method that can 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 this:

 bool predicate(T value) { return value == 1; } 

For more information on how the iterator block is compiled in Where (), there is a series explaining how they are compiled, starting here on Eric Lippert's blog.

+6
source

It filters the query to values ​​equal to 1. Consider

 IEnumerable<int> values = ...; IEnumerable<int> filteredValues = values.Where(x => x == 1); 

Another way to write this would be as follows

 public static IEnumerable<int> ExampleWhere(IEnumerable<int> values) { foreach (var x in values) { if (x == 1) { yield return 1; } } } 
+2
source

It depends on what the base collection is. This can make a huge difference if you are talking about LINQ to SQL, LINQ to Entities, or LINQ in general. If this is just an operator on a List , for example, it abbreviates for a foreach enumeration, where in the resulting enumeration only elements matching the condition are returned.

+2
source

He does this:

 IQueryable<int> seq = ...; return Queryable.Where(seq, Expression.Lambda(Expression.Equals(Expression.Constant(1), Expression.Parameter("x")))); 

This is a little simplified.

Edit: I have to admit that I'm talking about seq being IQueryable. In this case, the linq specifier does not matter.

+2
source

All Articles