Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between LINQ Queries & Lambda expression

Tags:

lambda

linq

Why to use lambda expression when we have LINQ queries just to shorten the length of code , increase the speed of development or is there any other reason which can only be achieved by Lambda expression & not by LINQ queries.

like image 684
Ulhas Tuscano Avatar asked Mar 16 '11 15:03

Ulhas Tuscano


1 Answers

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<T, bool> to act as the predicate, in which case things become ugly. So instead of writing:

Func<Foo, bool> predicate = ...; // Get predicate from somewhere
var query = from x in collection
            where predicate(x)
            select x;

I'd much rather write:

Func<Foo, bool> 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.

I have more information about how query expressions work in a blog post that you may be interested in.

like image 54
Jon Skeet Avatar answered Sep 26 '22 03:09

Jon Skeet