2
Reply

What is the difference between Lambda and Query Expression?

    Linq is always associated with Lambda Expressions. In .NET 2.0 we have the concept of Annonymous Methods that allows you to write function body inline without the need of writing a delegate function. Lambda Expression of .NET 3.5 is to consize the concept of Annonymous function writing. You can use Lambda Expressions when you want to create a delegate or an expression tree, basically. Here are some examples outside LINQ: The old-style List.ConvertAll/FindAll etc methods Starting new threads / tasks Attaching event handlers Providing an action in unit tests (e.g. "this action should throw an exception") Providing a value on request for Lazy Things which are only be achieved by Lambda expression & not by LINQ queries. There are some LINQ extension methods which do not have counterparts in LINQ query expressions, and will require the use of Lambda Expressions.

    Query expressions only cover a small subset of the LINQ operators, and are only applicable when you have the actual expression involved to hand, rather than (say) having a Func to act as the predicate, in which case things become ugly. So instead of writing:Func predicate = ...; // Get predicate from somewhere var query = from x in collectionwhere predicate(x)select x; I'd much rather write:Func predicate = ...; // Get predicate from somewhere var query = collection.Where(predicate); There are various other cases where using non-query expression syntax is simpler, particularly if your query only uses a single operator.Query expressions are effectively translated into non-query expressions, so anything you can do in query expressions can be expressed in non-query expressions. Use query expressions where they make the code simpler and more readable; don't use them where they don't