What are the pros and cons of LINQ operators and LINQ methods? Does one have limitations or added capabilities the other does not?
views:
32answers:
1
+2
A:
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
Jon Skeet
2010-09-05 19:53:04
Yes, that is what I meant. Query expressions versus dot notation.
Scott
2010-09-06 14:59:22
@Scott: Okay... so do the bullet points (which actually go into more detail than I intended) answer your question? Anything else you want to know?
Jon Skeet
2010-09-06 15:13:18
@Jon Skeet: Question answered. Thanks!
Scott
2010-09-06 15:18:51