我正在制作一些 C# 3 集合过滤器的原型(prototype)并遇到了这个问题。 我有一系列产品:
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();
问题:有什么区别,为什么要使用一个而不是另一个?
最佳答案
LINQ 会像您拥有的代码一样变成方法调用。
换句话说,应该没有区别。
但是,在您的两段代码中,您没有在第一段中调用 .ToList,因此第一段代码将生成一个可枚举的数据源,但如果您在其上调用 .ToList,则两者应该相同。
关于c# - 何时在 LINQtoObjects 上使用带有 lambda 的扩展方法来过滤集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5194/