The following expression
from item in items select item
Is syntactic sugar for this expression
items.Select(item => item)
The syntax format is literally translated in to the extension method format at compile time.
However, in your example only one of those statements uses a ToList
method, and therefore that method will enumerate or execute a query depending on whether items
is an Enumerable
or an IQueryable<>
, respectively.
As for which is better to use, that’s mostly opinion based. For me, I find that the LINQ syntax can provide clarity when doing joins. I use the extension method syntax for most other queries. Play with both and see which one makes sense for you within the context a particular query. Often one syntax will provide more clarity to the intent of the query than the other. Other times it doesn’t make any difference.
While we’re on the topic, it’s worth noting that the LINQ syntax works by pattern matching against available extension methods. This means from x in xs select x
won’t work if you haven’t imported an acceptable Select
extension method, because the syntax gets replace with that method. On a more dangerous note, you could import an entirely separate set of extension methods to match with the LINQ syntax, so long as those method signatures match what is expected by the syntax. And that functionality is extendable to custom types, as well, but I haven’t looked in to that recently.