16

我正在对一些 C# 3 集合过滤器进行原型设计并遇到了这个问题。我有一系列产品:

public class MyProduct
{
    public string Name { get; set; }
    public Double Price { get; set; }
    public string Description { get; set; }
}

var MyProducts = new  List<MyProduct>
{            
    new  MyProduct
    {
        Name = "Surfboard",
        Price = 144.99,
        Description = "Most important thing you will ever own."
    },
    new MyProduct
    {
        Name = "Leash",
        Price = 29.28,
        Description = "Keep important things close to you."
    }
    ,
    new MyProduct
    {
        Name = "Sun Screen",
        Price = 15.88,
        Description = "1000 SPF! Who Could ask for more?"
    }
};

现在,如果我使用 LINQ 进行过滤,它会按预期工作:

var d = (from mp in MyProducts
             where mp.Price < 50d
             select mp);

如果我将 Where 扩展方法与 Lambda 结合使用,过滤器也可以工作:

var f = MyProducts.Where(mp => mp.Price < 50d).ToList();

问题:有什么区别,为什么使用一个而不是另一个?

4

4 回答 4

6

LINQ 变成了方法调用,就像您拥有的代码一样。

换句话说,应该没有区别。

但是,在您的两段代码中,您没有在第一段调用 .ToList ,因此第一段代码将生成一个可枚举的数据源,但如果您在其上调用 .ToList ,则两者应该相同。

于 2008-08-07T19:25:49.487 回答
4

如前所述 d 将是IEnumerable<MyProduct>而 f 是List<MyProduct>

转换由 C# 编译器完成

var d = 
    from mp in MyProducts
    where mp.Price < 50d
    select mp;

转换为(在编译为 IL 并扩展泛型之前):

var d = 
    MyProducts.
    Where<MyProduct>( mp => mp.Price < 50d ).
    Select<MyProduct>( mp => mp ); 
    //note that this last select is optimised out if it makes no change

请注意,在这个简单的情况下,它几乎没有什么区别。Linq 真正有价值的地方在于更复杂的循环。

例如,该语句可以包括 group-bys、orders 和一些 let 语句,并且当等价物.Method().Method.Method()变得复杂时,仍然可以以 Linq 格式读取。

于 2008-08-11T12:52:52.080 回答
0

除了 ToList 差异之外,#2 更具可读性和自然 IMO

于 2008-08-08T04:19:00.847 回答
0

The syntax you are using for d will get transformed by the compiler into the same IL as the extension methods. The "SQL-like" syntax is supposed to be a more natural way to represent a LINQ expression (although I personally prefer the extension methods). As has already been pointed out, the first example will return an IEnumerable result while the second example will return a List result due to the call to ToList(). If you remove the ToList() call in the second example, they will both return the same result as Where returns an IEnumerable result.

于 2008-08-17T04:35:51.053 回答