Rectangle 27 0

delegates Can you explain lambda expressions?


// Only include children - a predicate
var query = dataSource.Where(person => person.Age < 18) 
                       // Transform to sequence of names - a projection
                      .Select(person => person.Name);

Basically as far as C# is concerned, lambda expressions are an easy way to create a delegate (or an expression tree, but let's leave those aside for now).

I saw this question and I thought, "Ooo! Maybe I can beat Jon Skeet to the punch!" But then I didn't. :) +1

In C# 1 we could only create delegate instances from normal methods. In C# 2 we gained anonymous methods. In C# 3 we gained lambda expressions, which are like more concise anonymous methods.

There was a brief, tangentially related discussion on Lippert's blog earlier this year about reading the "=>" operator: blogs.msdn.com/ericlippert/archive/2008/05/16/

There's a fuller discussion of this - along with other aspects - in my article on closures.

They're particularly concise when you want to express some logic which takes one value and returns a value. For instance, in the context of LINQ:

To me, Map suggests the creation of a map from key to value, where you can look up by key. Personally I'd prefer Project().

that code is looking pretty nice, even though I am pondering if Select is the right name. if you used Map, you'd arrive at relational algebra in code. :)

Note
Rectangle 27 0

delegates Can you explain lambda expressions?


[2*x for x in list]
def double(x):
    return 2*x
map(double, list) # iirc
double = lambda x : 2*x
map(double, list)

For example, in python, you want to double all elements in a list. There are pretty much three ways to do so:

So, a lambda in most languages is just a way to avoid the syntactic overhead of creating a new function.

Your final comment isn't necessarily true. lambdas provide the ability to create closures over variables as well.

with lambdas:

Note
Rectangle 27 0

delegates Can you explain lambda expressions?


Note
Rectangle 27 0

delegates Can you explain lambda expressions?


My main use of lambda expressions in .NET has been when working with lists. Using a lambda expression you can build up a query on a list in a similar way as you would build an SQL statement to search a database table.

Note