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);

其他回答

在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);

我知道这个问题是用c#标记的,但是VB.NET的Fluent语法非常冗长。

我刚刚建立了我们公司的标准,我们强制使用扩展方法。我认为在代码中选择一个而不是另一个是一个好主意,不要把它们混在一起。扩展方法读起来更像其他代码。

理解语法并没有所有的操作符,在查询周围使用圆括号和添加扩展方法只是在恳求我从一开始就使用扩展方法。

但在大多数情况下,这只是个人喜好,只有少数例外。

微软的文件如下:

作为一条规则,当你编写LINQ查询时,我们建议你尽可能使用查询语法,必要时使用方法语法。在两种不同的形式之间没有语义或性能上的差异。查询表达式通常比用方法语法编写的等效表达式更具可读性。

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/#query-expression-overview

他们还说:

要开始使用LINQ,你不需要大量使用lambdas。但是,某些查询只能用方法语法表示,其中一些查询需要lambda表达式。

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/query-syntax-and-method-syntax-in-linq

流畅的语法确实看起来更强大,它也应该更好地将代码组织成小的可重用方法。