What query am I able to perform with Lambda(Method Syntax) and not with (Query Syntax)?

.net, c#, lambda, linq

Solution

(This is a shorter answer than I was originally writing, but other answers have already provided some of the details.)

There are two reasons one might wish to use lambda expressions instead of query expressions:

Operations which simply aren't covered by query expressions, whether that's methods which aren't covered at all (e.g. `Count`) or overloads of operations which are included in query expressions, but not in that form. For example:

var indexedValues = values.Select((value, index) => new { value, index });

There's no query expression form which uses that overload.

When the lambda form is simpler. For example, if you've only got a single projection or filter, it can be simpler to do it in one call than set up the fluff of a query expression:

 var adults = people.Where(person => person.Age > 18);

Vs:

 var adults = from person in people
              where person.Age > 18
              select person;

Additionally, the lambda expression approach is somewhat tidier when you want to continue the expression after the query. For example, creating a list of the names of adults:

 var names = people.Where(person => person.Age > 18)
                   .Select(person => person.Name)
                   .ToList();

Vs:

 var names = (from person in people
              where person.Age > 18
              select person.Name).ToList();

The brackets end up being a bit irritating.

Where query expressions shine is in the operations which introduce transparent identifiers - joins, `SelectMany`, `let` etc. While you obviously can translate such code into lambda form, it can end up really ugly.

Problem

What query am I able to perform with Lambda(Method Syntax) and not with (Query Syntax)? The questions is simple, this is an example of both: ``` int[] numbers = { 5, 10, 8, 3, 6, 12}; //Query syntax: IEnumerable<int> numQuery1 = from num in numbers where num % 2 == 0 orderby num select num; //Method syntax: IEnumerable<int> numQuery2 = numbers.Where(num => num % 2 == 0).OrderBy(n => n); ``` What would be a query that I can perform Method Syntax and not in the Query Syntax?

Original source