Search code examples
c#linqlambda

What is the difference between method syntax and query syntax?


I know that this is LINQ:

var _Results = from item in _List
                where item.Value == 1
                select item;

And I know this is a lambda:

var _Results = _List.Where(x => x.Value == 1);

Editor's note: the above is not merely using lambdas, it is LINQ using the "Method Syntax" whose predicate is a lambda. To be clear, both of the above samples are LINQ (my original post was incorrect, but I left the error to illustrate the confusion prompting the question).

But is LINQ a subset of lambdas, or what?

Why are there two seemingly identical technologies?

Is there a technical reason to choose one over the other?


Solution

  • This is LINQ (using query syntax):

    var _Results = from item in _List
                    where item.Value == 1
                    select item;
    

    This is also LINQ (using method syntax):

    var _Results = _List.Where(x => x.Value == 1);
    

    It's interesting to note that both of these flavors will end up producing the exact same code. The compiler offers you a service by allowing you to express your wishes in the manner that you prefer.

    And this is a lambda:

    x => x.Value == 1
    

    When you choose to use method syntax, LINQ is almost always seen around lambda expressions. But LINQ and lambdas are two totally different things, both of which can be used by themselves.

    Update: As svick rightly points out, LINQ with query syntax is also implemented using lambda expressions (as mentioned earlier, the compiler allows you to write in query syntax but effectively transforms it to method syntax behind your back). This is just piling on the fact that both flavors are totally equivalent and will behave the same way (e.g. lambda expressions may cause closures to be created).