How does LINQ's “Where” method works?

后端 未结 3 2001
无人及你
无人及你 2021-01-21 10:24

Exactly how LINQ\'s \"where\" method is defined? I\'m guessing implementation is something like this:

public static IEnumerable Where ( this partialPare         


        
3条回答
  •  礼貌的吻别
    2021-01-21 10:32

    In the case of linq-to-objects, you can consider it to be the equivalent of enumeration.Where(c => c.Col1 == c.Col2) or enuemration.Where(c => c.Col1 == c.Col2 || c.Col3 == c.Col4).

    The easiest way to implement Where would be something like:

    public static IEnumerable Where(this IEnumerable src, Func pred)
    {
      foreach(T item in src)
        if(pred(item))
          yield return item;
    }
    

    Though if you look at the code in reflector you'll see a lot of optimisations on this basic idea.

    However, it this call to Where is just one way that where could implemented. Because LINQ queries can be executed against lots of different queryable sources, there are other possibilities. It could for example be turned into a SQL WHERE clause on a query sent to the database. It can be informative to execute some queries using Linq2SQL, and run a SQL Profiler and look at what is sent to the server.

提交回复
热议问题