Lambda Expressions
Lambda expressions are part of .Net 3.0. They are used extensively in Linq, but they can also be used on their own. With Lambda expressions, filtering and sorting Lists has become a lot easier.
I'm going to filter and sort Lists of Employee objects:
|
FindAll( )
Suppose I have a List of Employees, and I want to find all the managers. At one point I would have written code like this:
|
The new syntax with Lambda expressions is clean and simple:
|
Note that the term "employee" was used to make things clear. I could have used any other name. For example:
|
Where( )
Where( ) works exactly the same way as FindAll( ). In some cases, using Where( ) instead of FindAll( ) can make your code easier to understand. Here, for example, is a different way to find all the managers:
|
Find( )
Find( ) returns the first object in a list which meets my search criteria. If no object meets my criteria, it returns null.
|
ForEach( )
ForEach( ) can be used to perform an operation on each item in a List. In this example we are adding 100 to the Salary of each Employee:
|
OrderBy( ) and OrderByDescending( )
OrderBy( ) returns a List sorted in ascending order. OrderByDescending( ) returns a List sorted in descending order. This only works if there is an appropriate method to do the comparison. For basic data types (e.g., string, int, decimal, etc.), Lambda expressions make sorting easy:
|
Note that the original List, employees, is unchanged. Of course, you could sort the employees List itself as follows:
|
To sort in descending order:
|
Sort( )
Sort( ) provides an alternative to OrderBy( ):
|
Note that Sort( ) operates on the orginal List, employees. That is, there is no need to do this:
|
because employees is already sorted.
Getting Fancy
If I make an enum like this:
|
and I add this method to the Employee class:
|
Now I can sort my List of Employees like this:
|
or this:
Employee .Sort(employees, e => e.LastName, SortOrder.Descending); |
Comments
Post a Comment