开发者

Linq.Where(x=>x==1) - What Is The Compiler Doing

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;
    }
  }
}


It kind of depends upon what the underlying collection is. It can make a huge difference if you're talking about LINQ to SQL, LINQ to Entities, or LINQ in general. If this is just a statement on a List for instance, it's basically shorthand for the foreach enumerator where only items matching the condition are returned in the resulting enumeration.


It is doing this:

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

This is only slightly simplified.

Edit: I should qualify that I am talking about the case that seq is an IQueryable. The specifiy linq provider does not matter in this case.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜