8

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.

2
  • Usually one of the two is more succinct, depending on the problem - you should use both as appropriate Commented Mar 16, 2011 at 15:57
  • 1
    @BrokenGlass: It would definitely be pretty rare for them to be exactly the same in length :) Commented Mar 16, 2011 at 15:59

2 Answers 2

21

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 I think I invariably use then together when I write a Query Expression
3

any other reason which can 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. A good example is Enumerable.ToLookup - if you want to create an ILookup, you need to use lambdas to generate this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.