开发者

LINQ operators versus LINQ methods: limitations, pros / cons of one over the other?

开发者 https://www.devze.com 2023-01-14 18:08 出处:网络
What are the pros and cons of LINQ operators and LINQ methods? Does one have limitations or added c开发者_StackOverflow社区apabilities the other does not?The term \"operator\" in LINQ isn\'t the same

What are the pros and cons of LINQ operators and LINQ methods? Does one have limitations or added c开发者_StackOverflow社区apabilities the other does not?


The term "operator" in LINQ isn't the same as "operator" in the normal sense of C# language operators, (+, && etc). The LINQ standard query operators are just the LINQ methods which are expected to be available where possible through most providers (and the ones made available through LINQ to Objects in particular).

Were you actually asking about the pros and cons of using query expressions like this:

var query = from item in source
            where item.SomeProperty == 5
            select item.OtherProperty;

vs the "fluent interface" or "dot notation" of normal extension method calls:

var query = source.Where(item => item.SomeProperty == 5)
                  .Select(item => item.OtherProperty);

? If so, I can write about that in more detail, but basically:

  • There'll generally be no performance difference, as query expressions are effectively translated by the compiler into the latter syntax. Occasionally there are overloads you can use from dot notation which aren't available via query expressions, and you may be able to make things more efficient that way.
  • Operators which use multiple delegates (e.g. Join, GroupBy) tend to be more readable in query expression syntax
  • If your query would use lots of transparent identifiers in query expression syntax, the dot notation is likely to be ugly
  • If your query is very simple (just a Where and/or Select) then dot notation is likely to be simpler
  • If you're using methods which are unsupported by query expressions (e.g. Count(), ToList() etc) then having to bracket the query expression can be ugly
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号