Fluent and Query Expression — Is there any benefit(s) of one over other?

后端 未结 13 1474
一向
一向 2020-11-22 05:15

LINQ is one of the greatest improvements to .NET since generics and it saves me tons of time, and lines of code. However, the fluent syntax seems to come much more natural

13条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 06:03

    In VB.NET i very much prefer query syntax.

    I hate to repeat the ugly Function-keyword:

    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)
    

    This neat query is much more readable and maintainable in my opinion:

    query = From fullName In fullNames
            From name In fullName.Split()
            Order By fullName, name
            Select name & " came from " & fullName
    

    VB.NET's query syntax is also more powerful and less verbose than in C#: https://stackoverflow.com/a/6515130/284240

    For example this LINQ to DataSet(Objects) query

    VB.NET:

    Dim first10Rows = From r In dataTable1 Take 10
    

    C#:

    var first10Rows = (from r in dataTable1.AsEnumerable() 
                       select r)
                       .Take(10);
    

提交回复
热议问题