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

后端 未结 13 1449
一向
一向 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 05:59

    I prefer to use the latter (sometimes called "query comprehension syntax") when I can write the whole expression that way.

    var titlesQuery = from e in entries
                      where e.Approved
                      orderby e.Rating
                      select e.Titles;
    
    var title = titlesQuery.FirstOrDefault();
    

    As soon as I have to add (parentheses) and .MethodCalls(), I change.

    When I use the former, I usually put one clause per line, like this:

    var title = entries
        .Where (e => e.Approved)
        .OrderBy (e => e.Rating)
        .Select (e => e.Title)
        .FirstOrDefault();
    

    I find that a little easier to read.

提交回复
热议问题