Lambda Expressions
A Lambda expression is a very efficient mechanism for coding a method which can
be used directly as a parameter to another method. This may seem obscure, but a
simple example will help.
Suppose we have a list of books and we want to find the average cost of the
books. The traditional approach would mean we write an loop to retrieve each
book in turn. We add the proce of the book to a running total and once the loop
finishes we divide by the number of books.
However, we know we have an extension method in LINQ called Average. This method
needs to know which value to average so a description of it operation might be:
Go through the list of books and find the average of the Price field. In
C#/pseudo code this would be:
double ave = books.Average(use the price of the book)
This means we have to provide a function that the Average method will call -
passing it the current book and asking for a data value to use in the
calculation. Earlier versions of C# used the concept of a 'delegate' method to
provide this function, and the syntax was tedious and spread over several chunks
of code. With Lambda syntax we can express this much more efficiently. Our code
becomes:
double ave = books.Average(b => b.Price);
The Lambda expression passed into the Average mthod can be read as follows:
- Use a local variable called 'b' to handle the current book being processed.
- Using variable 'b' give me the value of 'b.Price'
The Lambda expression can include logic and function calls on the right hand
side of the =>, and it can use multiple variables on the left hand side, for
more complex scenarios.
Suppose we want to retrieve a list of expensive books (e.g. Price > £20). Our
code would look something like this:
IEnumerable<Book> expensivebooks = books.Where(b => b.Price > 20);
There is far more to Lambda expressions than these two examples can hope to
demonstrate. The more advanced features/usage are exploited by developers who
build sophisticated extensions to the code libraries, for example the .NET
Framework LINQ libraries themselves. These uses are beyond the scope of this
brief introduction.