Is there a situation where the use of the lambda expression is particularly helpful or its mainly usage is to write less code?
Asked
Active
Viewed 458 times
7
-
10Isn't writing more concise and readable code already particularly helpful? – Joey Feb 27 '10 at 15:22
-
2Eh eh, sure it is. But I would like to know if it is the only topic... :-) – Maurizio Reginelli Feb 27 '10 at 15:31
-
Take a look at John Skeet's SO answer [here](http://stackoverflow.com/questions/187414/can-you-explain-lambda-expressions-closed). And here is another SO question [with specific uses of lambdas](http://stackoverflow.com/questions/1954909/please-list-specific-examples-of-the-benefits-of-using-lambda-expressions) – David Robbins Feb 27 '10 at 15:27
2 Answers
19
The justification for adding lambdas to the language was two things.
(1) They make syntactic transformation of query comprehensions possible. When you say
from customer in customers
where customer.City == "London"
select customer
That becomes
customers.Where(customer=>customer.City == "London")
(2) They can be turned into expression trees, and thereby make LINQ-to-SQL, LINQ-to-Entities, and so on, possible. That is, they can represent both the ability to do their semantics and the ability to inspect their structure.

Eric Lippert
- 647,829
- 179
- 1,238
- 2,067
-
Could you provide an example of an expression tree, please? Thanks – Maurizio Reginelli Feb 27 '10 at 15:49
-
6
-
@Maurizio: http://blogs.msdn.com/charlie/archive/2008/01/31/expression-tree-basics.aspx – Eric Lippert Feb 27 '10 at 16:31
2
Lambda expressions are syntactic sugar for anonymous methods, and their use cases are mostly the same.
Lambdas can also be converted to expression trees.
As they are much shorter and easier to write (at least for the simple cases), that in itself is helpful.

Oded
- 489,969
- 99
- 883
- 1,009
-
-
1Not *quite* the same - lambda expressions can also be converted into expression trees, whereas anonymous methods can't. (There's no such term as "anonymous delegate" - there are *anonymous methods*, and *anonymous functions* - that latter is a term covering both anonymous methods an lambda expressions. – Jon Skeet Feb 27 '10 at 15:27