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();
两者之间有什么区别吗?或者两者之间有什么特别的好处吗?
在VB。NET我非常喜欢查询语法。
我讨厌重复丑陋的函数关键字:
Dim fullNames = { "Anne Williams", "John Fred Smith", "Sue Green" };
Dim query =
fullNames.SelectMany(Function(fName) fName.Split().
Select(Function(Name) New With {Name, fName})).
OrderBy(Function(x) x.fName).
ThenBy(Function(x) x.Name).
Select(Function(x) x.Name & " came from " & x.fName)
在我看来,这个简洁的查询更具可读性和可维护性:
query = From fullName In fullNames
From name In fullName.Split()
Order By fullName, name
Select name & " came from " & fullName
VB。NET的查询语法也比c#更强大,更简洁:https://stackoverflow.com/a/6515130/284240
例如,这个LINQ到数据集(对象)查询
VB。NET:
Dim first10Rows = From r In dataTable1 Take 10
C#:
var first10Rows = (from r in dataTable1.AsEnumerable()
select r)
.Take(10);