SIGN UP MEMBER LOGIN:    
ARTICLE

Lambda Expressions are Wonderful

Posted by Andrew Fenster Articles | C# Language December 02, 2009
Lambda expressions are simple to use and make routine tasks such as sorting or filtering Lists much easier.
Reader Level:

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.

In my examples, I'm going to filter and sort Lists of Employee objects:

public class Employee

{
    public string FirstName {set; get;}
    public string LastName {set; get;}
    public decimal Salary {set; get;}
    public bool IsManager {set; get;}
}

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:

List<Employee> managers = new List<Employee>( );
foreach (Employee employee in employees)
{
    if (employee.IsManager == true)
        managers.Add(employee);
}

The new syntax with Lambda expressions is clean and simple:

 List<Employee> managers = employees.FindAll(employee => employee.IsManager == true);

Note that the term "employee" was used to make things clear.  I could have used any other name.  For example:

 List<Employee> managers = employees.FindAll(e => e.IsManager == true);

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:

using System.Linq;

foreach (Employee employee in employees.Where(e => e.IsManager == true))
{
    // do something
}

Find( )

Find( ) returns the first object in a list which meets my search criteria.  If no object meets my criteria, it returns null.

Employee firstManager = employees.Find(employee => employee.IsManager == true);

if (firstManager == null)
    Console.WriteLine("No managers found in list.");

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:

 employees.ForEach(e => e.Salary += 100);

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:

using System.Linq; 

List
<Employee> sortedList = employees.OrderBy(e => e.Age).ToList();

Note that the original List, employees, is unchanged.  Of course, you could sort the employees List itself as follows:

 employees = employees.OrderBy(e => e.Age).ToList();

To sort in descending order:

 List<Employee> sortedList = employees.OrderByDescending(e => e.Age).ToList();

Sort( )

Sort( ) provides an alternative to OrderBy( ):

 employees.Sort((e1, e2) => e1.DOB.CompareTo(e2.DOB));

Note that Sort( ) operates on the orginal List, employees.  That is, there is no need to do this:

 employees = employees.Sort((e1, e2) => e1.DOB.CompareTo(e2.DOB));

because employees is already sorted.

Getting Fancy

If I make an enum like this:

 public enum SortOrder { Ascending, Decending }

and I add this method to the Employee class:

public static void Sort<TKey>(ref List<Employee> list, Func<Employee, TKey> sortKey, 
    SortOrder sortOrder)
{
    if (sortOrder == SortOrder.Ascending)
        list = list.OrderBy(sortKey).ToList();
    else
        list = list.OrderByDescending(sortKey).ToList();
}

Now I can sort my List of Employees like this:

 Employee.Sort(employees, e => e.Salary, SortOrder.Ascending);

or this:

Employee.Sort(employees, e => e.LastName, SortOrder.Descending);


In this article, I've only discussed the use of Lambda expressions to sort and filter Lists of objects.  If that were the only use for Lambda expressions, they would still be a major time saver - a fantastic new addition to .Net.  Lambda expressions, however, have many uses.  Once you get started, you will wonder how you ever managed without them.

Enjoy.

Login to add your contents and source code to this article
share this article :
post comment
 

Perhaps you need to try fewer languages and get a better handle on the one or two that you prefer to use the most. If you are doing anything with MS and .Net, Lambda Expressions are here to stay and do indeed make life a little more simple and code mush easier to read.

Posted by gfw Dec 27, 2009

Good article and easy to understand.  Thanks.

Posted by gfw Dec 27, 2009

This article is an example of why I like C# Corner.  It's simple and easy to follow, so I can get a quick introduction to the topic without time-consuming complexity.  Well done!

==============

The feedback mechanism for this site could be improved, however.  The User ID is case-sensitive, which is unusual.  Also when I submitted my comment, the site asked me to log in, the ID I typed didn't match the original case, so was rejected.  I selected the "forgot password" link and got the password, BUT THE SITE THREW AWAY THE COMMENTS I HAD ENTERED!  This wastes peoples' time.

Posted by Alan C Balkany Dec 23, 2009

I did not learn much from this article even though I have 3 years of coding in many languages and databases. I was not able to understand much but I have many years coding  and work in many fields.

Posted by Abdul Miriki Dec 04, 2009

Man, I have been serching for something like this for a long time.
You saved me countless hours of coding.
Thank you Andy, good work!

Ping-Fu

Posted by Ping Fu Dec 02, 2009
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
    Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites - Click Here!
Become a Sponsor