两者都更好:它们满足不同的需求。当您想利用多个范围变量时,查询语法就会发挥作用。这在三种情况下发生:
- 使用let关键字时
- 当您有多个生成器(from子句)时
- 加入时
这是一个示例(来自LINQPad示例):
string[] fullNames = { "Anne Williams", "John Fred Smith", "Sue Green" };
var query =
from fullName in fullNames
from name in fullName.Split()
orderby fullName, name
select name + " came from " + fullName;
现在将此与方法语法中的相同内容进行比较:
var query = fullNames
.SelectMany (fName => fName.Split().Select (name => new { name, fName } ))
.OrderBy (x => x.fName)
.ThenBy (x => x.name)
.Select (x => x.name + " came from " + x.fName);
另一方面,方法语法可显示查询运算符的全部范围,并且对于简单查询更为简洁。通过混合查询和方法语法,您可以兼得两者。这通常在LINQ to SQL查询中完成:
var query =
from c in db.Customers
let totalSpend = c.Purchases.Sum (p => p.Price) // Method syntax here
where totalSpend > 1000
from p in c.Purchases
select new { p.Description, totalSpend, c.Address.State };