LINQ query syntax translates directly to extension method syntax. However, the reverse is not true. There are way more extension methods than supported by the LINQ query syntax keywords.
So, with method syntax you can do exactly the same or more than with LINQ query syntax. Usually LINQ query syntax is nicer to read.
// LINQ query syntax
var query =
from num in numbers
where num % 2 == 0
orderby num
select num;
// Corresponding method syntax
var query = numbers
.Where(num => num % 2 == 0)
.OrderBy(num => num)
.Select(num => num);
A simple example of what you can do with method syntax and not with query syntax (since there are no keywords for it):
var query = numbers
.First();
You can combine both if you want:
var query =
(from num in numbers
where num % 2 == 0
orderby num
select num)
.First();
Apart from First
, there are tons of LINQ extension methods (Sum
, Average
, Max
...) that have no keywords in LINQ query syntax.
By the way, because LINQ query syntax maps to extension methods, you are not restricted to using LINQ extension methods. If you define on your own custom objects a Select
and Where
method that both accept a delegate, then you can use LINQ query syntax on your own objects! How cool is that? For example, a nonsensical example:
public class MyClass
{
public MyClass Where(Func<string, bool> function)
{
return this;
}
public List<string> Select(Func<string, string> function)
{
return new List<string>();
}
}
MyClass myClass = new MyClass();
var x = from m in myClass
where !String.IsNullOrEmpty(m)
select m;