代码之家  ›  专栏  ›  技术社区  ›  kofucii

LINQ的“Where”方法是如何工作的?

  •  3
  • kofucii  · 技术社区  · 14 年前

    LINQ的“where”方法究竟是如何定义的?我猜实现是这样的:

    public static IEnumerable<T> Where ( this partialParent, Func<bla,bla> myDelegate ) 
    

    from c in context.Con
    where ( c.Col1 == c.Col2 )
    select c
    

    我猜是的 "c.Col1 == c.Col2" 是传下来的 foreach 循环执行检查。但当我这样调用where时发生了什么:

    where ( c.Col1 == c.Col2 || c.Col3 == c.Col4 )
    

    这两个“检查”是作为一个整体来传递的吗?也许我错过了一些很简单的事情。

    3 回复  |  直到 14 年前
        1
  •  0
  •   Andrew Barber Eric Lafortune    14 年前

    您提到的查询语法 where 基本上创建一个方法和委托,并用它调用方法语法版本。不管你叫什么 哪里 with被转换为单个方法,然后通过源序列的每个元素上的委托调用。

    所以可能你所说的两个检查作为一个完整的表达式被传递,这就是正在发生的事情。。。

    where ( c.Col1 == c.Col2 || c.Col3 == c.Col4 )
    

    它变成了这样一个单一的方法调用:

    bool MethodExample(var c){
      return ( c.Col1 == c.Col2 || c.Col3 == c.Col4 );
    }
    

    然后对每个元素调用。(显然上面是伪代码)

        2
  •  3
  •   Jon Hanna    14 年前

    enumeration.Where(c => c.Col1 == c.Col2) enuemration.Where(c => c.Col1 == c.Col2 || c.Col3 == c.Col4) .

    最简单的实现方法 Where

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

    不过,如果你看看reflector中的代码,你会看到很多关于这个基本思想的优化。

    然而,这一呼吁 在哪里? 只是一种方式 where WHERE 子句来处理发送到数据库的查询。使用Linq2SQL执行一些查询,运行SQL探查器并查看发送到服务器的内容,这些都是有用的。

        3
  •  2
  •   Fredrik Mörk    14 年前

    // first
    from item in sequence
    where expression
    select item;
    
    // second
    sequence.Where(item => expression);
    

    不管在中国做了多少比较 表达 只要它产生一个布尔结果。这仍然是一种表达。

    这意味着以下两项也完全相同:

    // first
    from c in context.Con
    where ( c.Col1 == c.Col2 || c.Col3 == c.Col4 )
    select c;
    
    // second
    context.Con.Where(c => c.Col1 == c.Col2 || c.Col3 == c.Col4);