Introduction
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() function in C#
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. 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() function in C#
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() function in C#
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() loop in C#
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() functions in C#
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. 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() function in C#
Sort( ) provides an alternative to OrderBy( ):
employees.Sort((e1, e2) => e1.DOB.CompareTo(e2.DOB));
Note. The 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.

Rushi MehtaPosted Mar 6, 2020, 3:21 AM
Good article and easy to understand. Thanks for sharing
Kevin SheaPosted Sep 8, 2015, 7:26 AM
To discuss the other POV, and give a word or two of caution - lambda expressions *can* be easier to read but not always.There's a tendency when a new "cool" feature appears for it to be (over) used everywhere and as a result in places it shouldn't. I've seen seen your for loop split into 5 tests filtering out expressions being much easier to read than the more declarative style lambda. More importantly, if you start using "e.IsManager" as a lambda filter in many places, what happens when your criteria changes to something like "a manager or person with delegated responsibilities"? Be careful, its very easy to violate the DRY principle with lambdas
Mahesh ChandPosted Oct 1, 2012, 12:06 AM
Abdul, Lamda Exp are a new and advanced concept. If you are not an expert programmer, you probably won't understand it. Keep working harder.
gfweditedPosted Dec 27, 2009, 3:43 PMEdited Dec 27, 2009, 3:47 PM
Good article and easy to understand. Thanks.
Alan C BalkanyPosted Dec 23, 2009, 11:52 AM
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.
Abdul MirikiPosted Dec 4, 2009, 6:54 PM
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.
Ping FuPosted Dec 2, 2009, 7:28 PM
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