To make it more general:
from item in someSource select new{item.Something}
someSource.Select(item => new{item.Something}
from item in someSource where item.SomeProperty == someValue
someSource.Where(item => new{item.Something}
from item in someSource group item.Property1 by item.Property2
someSource.GroupBy(item => item.Property2, item => item.Property1)
from item in someSource orderby item.Property1
someSource.OrderBy(item => item.Property1)
from item in someSource orderby item.Property1 descending
someSource.OrderByDescending(item => item.Property1)
Some of the first form of each are not complete as they need to end with a select
or a group by
. This doesn't apply to the second form, so you have a complete query in the .OrderBy
even though you don't after orderby
. When converting, remember that .Select(x => x)
can be added to every query and make no logical difference, by equivalence, with the last example of orderby descending
adding select item
to the end makes it a complete query that is equivalent to the OrderByDescending
given below.
Adding several together:
from item in someSource
where item.Property1 == 43
orderby item.Property2
select new {item.Property3, item.Property4}
someSource
.Where(item => item.Propert1 == 43)
.OrderBy(item => item.Propert2)
.Select(item => new{item.Propert3, item.Property4});
Because each method call is separate, we don't need to use the same terms in the lambda with the second type, so this is equivalent to:
someSource
.Where(x=> x.Propert1 == 43)
.OrderBy(y=> y.Propert2)
.Select(z=> new{z.Propert3, z.Property4});
But we can't do that with the first form, because it's a single clause with each term defined only once. Because the methods are all extensions, it is also equivalent to:
Queryable.Select(
Queryable.OrderBy(
Queryable.Where(someSource, x => x.Propert1 == 43),
y=> y.Propert2),
z=> new{z.Propert3, z.Property4});
OR
Enumerable.Select(
Enumerable.OrderBy(
Enumerable.Where(someSource, x => x.Propert1 == 43),
y=> y.Propert2),
z=> new{z.Propert3, z.Property4});
Which will work with any .NET language, even without support for Linq or extension methods in that language.
LinqPad is great for examining queries (or any C# code) in a variety of ways, and one of them is turning the query syntax into the equivalent method syntax (the former is compiled to the latter, anyway).
Personally, I find I switch between the two a lot. I'll favour query syntax for larger queries, and I'll favour method syntax if the overall expression contains a high ratio of calls that don't have a query syntax equivalent to those that do, but there are plenty where it's just a matter of whatever I typed at the time.