LINQ是自。泛型以来对.NET的最大改进之一,它为我节省了大量时间和代码行。但是,对我来说,流利的语法似乎比查询表达式语法自然得多。
var title = entries.Where(e => e.Approved) .OrderBy(e => e.Rating).Select(e => e.Title) .FirstOrDefault(); var query = (from e in entries where e.Approved orderby e.Rating select e.Title).FirstOrDefault();
两者之间是否有任何区别,或者两者之间有什么特别的好处?
两者都更好:它们满足不同的需求。当您想利用 多个范围变量 时,查询语法就会发挥作用。这在三种情况下发生:
这是一个示例(来自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 };