Sometimes if you have a set of records in a List, it becomes quite easy to query on a list using a Lamda Expression. This article exemplifies methods for performing several tasks and queries over a list. A sample code is also attached with this article to explain the use of Lambda Expressions.
Suppose we have a "Person" class that has the following members:
class Person
{
public string SSN;
public string Name;
public string Address;
public int Age;
public Person(string ssn, string name, string addr, int age)
{
SSN = ssn;
Name = name;
Address = addr;
Age = age;
}
}
Now we create a list of the Person objects in which we have to perform several operations like finding a person on certain conditions, removing a person's record etc. These types of operations can be easily performed using a "Lambda Expression". We create the list and populate them in the following way:
List<Person> listPersonsInCity = new List<Person>();
listPersonsInCity.Add(new Person("203456876", "John", "12 Main Street, Newyork, NY", 15));
listPersonsInCity.Add(new Person("203456877", "SAM", "13 Main Ct, Newyork, NY", 25));
listPersonsInCity.Add(new Person("203456878", "Elan", "14 Main Street, Newyork, NY", 35));
listPersonsInCity.Add(new Person("203456879", "Smith", "12 Main Street, Newyork, NY", 45));
listPersonsInCity.Add(new Person("203456880", "SAM", "345 Main Ave, Dayton, OH", 55));
listPersonsInCity.Add(new Person("203456881", "Sue", "32 Cranbrook Rd, Newyork, NY", 65));
listPersonsInCity.Add(new Person("203456882", "Winston", "1208 Alex St, Newyork, NY", 65));
listPersonsInCity.Add(new Person("203456883", "Mac", "126 Province Ave, Baltimore, NY", 85));
listPersonsInCity.Add(new Person("203456884", "SAM", "126 Province Ave, Baltimore, NY", 95));
Now we see how we can do various complex operations on the list using a one-line simple Lambda expression.
- The following code retrieves the first two persons from the list who are older than 60 years:
Console.WriteLine("\n-----------------------------------------------------------------------------"); Console.WriteLine("Retrieving Top 2 aged persons from the list who are older than 60 years\n"); foreach (Person person in listPersonsInCity.FindAll(e => (e.Age >= 60)).Take(2).ToList()) { Console.WriteLine("Name : " + person.Name + " \t\tAge: " + person.Age); }
- The following code checks any person's age that is between 13 and 19 years:
Console.WriteLine("\nChecking whether any person is teen-ager or not..."); if (listPersonsInCity.Any(e => (e.Age >= 13 && e.Age <= 19))) { Console.WriteLine("Yes, we have some teen-agers in the list"); }
- The following code checks whether all the people's ages are greater than Ten years or not:
Console.WriteLine("\nCheking whether all the persons are older than 10 years or not..."); if ( listPersonsInCity.All(e => (e.Age > 10))) { Console.WriteLine("Yes, all the persons older than 10 years"); }
- The following code gets the average of all the people's ages:
Console.WriteLine("\nGetting Average of all the person's age..."); double avgAge = listPersonsInCity.Average(e => e.Age); Console.WriteLine("The average of all the person's age is: "+ avgAge);
- The following code checks whether a person having the name 'SAM' exists or not:
Console.WriteLine("\nChecking whether a person having name 'SAM' exists or not..."); if (listPersonsInCity.Exists(e => e.Name == "SAM")) { Console.WriteLine("Yes, A person having name 'SAM' exists in our list"); }
- The following code checks at what position a person having the name 'Smith' exists in the list:
Console.WriteLine("\nChecking the index position of a person having name 'Smith' ..."); int indexForSmith = listPersonsInCity.FindIndex(e => e.Name == "Smith"); Console.WriteLine("In the list, The index position of a person having name 'Smith' is : " + indexForSmith);
- The following code retrieves the oldest person in the list:
Console.WriteLine("\nGetting the name of the most aged person in the list ..."); Person p = listPersonsInCity.First(m=> m.Age == (listPersonsInCity.Max(e => e.Age))); Console.WriteLine("The most aged person in our list is: "+ p.Name +" whose age is: "+ p.Age);
- The following code gets the total of all the people's ages:
Console.WriteLine("\nGetting Sum of all the person's age..."); int sumOfAges = listPersonsInCity.Sum(e => e.Age); Console.WriteLine("The sum of all the persons's age = "+ sumOfAges);
- The following code skips each person whose age is less than 60:
Console.WriteLine("\nSkipping every person whose age is less than 60 years..."); foreach (Person pers in listPersonsInCity.SkipWhile(e => e.Age < 60)) { Console.WriteLine("Name : "+ pers.Name + " \t\tAge: "+ pers.Age); }
- The following code retrieves all the people until we find a person with a name beginning with any letter other than "S" :
Console.WriteLine("Displaying the persons until we find a person with name starts with other than 'S'"); foreach (Person pers in listPersonsInCity.TakeWhile(e => e.Name.StartsWith("J"))) { Console.WriteLine("Name : " + pers.Name + " \t\tAge: " + pers.Age); }
- The following code checks whether all the people have their SSN or not:
Console.WriteLine("\nChecking all the persons have SSN or not ..."); if(listPersonsInCity.TrueForAll(e => e.SSN != null)) { Console.WriteLine("No person is found without SSN"); }
- The following code removes all the people having the name "SAM":
Console.WriteLine("\nRemoving all the persons record from list that have "SAM" name"); listPersonsInCity.RemoveAll(e => (e.Name == "SAM")); if (listPersonsInCity.TrueForAll(e => e.Name != "SAM")) { Console.WriteLine("No person is found with 'SAM' name in current list"); }
- The following code searches for the person having "203456876" as their SSN:
Console.WriteLine("\nFinding the person whose SSN = 203456876 in the list"); Person oPerson = listPersonsInCity.Find(e => (e.SSN == "203456876")); Console.WriteLine("The person having SSN '203456876' is : " + oPerson.Name + " \t\tAge: " + oPerson.Age);

Dinesh GabhanePosted Nov 12, 2019, 11:56 PM
Very Good Article
Himani PatelPosted Feb 16, 2016, 2:37 PM
thank you so much it really helped me a lot :)
ricardo jrPosted May 17, 2013, 1:15 PM
Hi Hermant, thanks for the help! But my problem is that I need analyze a given string like "data > "\"17/05/2013\"" or "code <= "\"123456\"", "data" and "code" can be string attributes from a class, and can be from different classes. After analyzing the string I need make a lambda expression that execute the filtering. For example, I have a class public class Element { public string Name; public double Number; public string data; } var items = new List<Element>() { new Element("a", 1000 ,"13-12-2012 10:47:00:000"), new Element("b", 900 ,"13-12-2012 10:48:00:345"), new Element("b", 800 ,"13-12-2012 10:48:00:545"), new Element("d", 700 ,"13-12-2012 11:48:00:545"), new Element("e", 600 ,"13-12-2012 12:48:00:545"), new Element("x", 500.5 ,"13-12-2012 14:48:00:545"), new Element("y", 400 ,"13-12-2012 15:48:00:545"), new Element("z", 300 ,"13-12-2012 16:48:00:545") }; and for filter on Number I do: string s = "Number >= 500.50 && Number < 1000"; var pred = SimpleExpression.PredicateParser<Element>.Parse(s); var f = pred.Compile(); Now q has my filtered list by query: var q = from e in items where f(e) select e; The SimpleExpression.PredicateParser fails when analize "data > "\"17/05/2013\"" because both are strings. My work to do is make a analizer that generate a expression that can be used on var q = from e in items where f(e) select e; f(e) returns bool, so, if I use IComparer and IComparable I only can return int from Compare and CompareTo. The predicate parser that I using is from http://www.codeproject.com/Tips/355513/Invent-your-own-Dynamic-LINQ-parser thanks!
Hemant SrivastavaPosted May 17, 2013, 12:34 AM
Hi Ricardo, In that situation, You need to implement IComparable interface for Person class. Refer to following link http://support.microsoft.com/kb/320727
ricardo jrPosted May 16, 2013, 1:09 PM
Hi, I trying to do something like list all SSN >= "203456879", for example. My problem is that both types are strings and comparison is different than numeric types. Does someone have a clue?
wen zePosted Dec 10, 2012, 2:07 AM
Thanks for your sharing.
Gaurav GuptaPosted Oct 17, 2012, 2:14 AM
Thanks for sharing. I read that...
Hemant SrivastavaPosted Oct 15, 2012, 10:46 AM
@Gaurav Gupta: How to use lambda expression on a DataTable object, you can see my new article at: http://www.c-sharpcorner.com/UploadFile/0f68f2/querying-a-data-table-using-select-method-and-lambda-express/
Hemant SrivastavaPosted Oct 11, 2012, 9:20 PM
@shweta garg: Hi Shweta, Wherever we are getting a list of objects after using lambda expression, we could use "Count" property to get the number of occurances ... For example: listPersonsInCity.FindAll(e => (e.Age >= 60)).Count
Hemant SrivastavaPosted Oct 11, 2012, 8:18 PM
@Gaurav Gupta: ..... Thanks Gaurav.. Yes we can use lambda expression on data table object. I am going to write another article of using lamda expression over Data table...Wait for a few days ....
shweta gargPosted Oct 11, 2012, 12:53 AM
Nice explanation Sir....Sir can we count the number of occurrences of each value in the list?
Megha GoyalPosted Oct 11, 2012, 12:27 AM
It is easily understandable article. By this we come to know that how to perform search operation on list using lamda expression.Really very impressive
Tina GargPosted Oct 10, 2012, 11:42 PM
Very nice explanation Hemant Sir..It is very useful for me.Thanks
Gaurav ChauhanPosted Oct 10, 2012, 11:23 PM
Very useful article.
lavisha rastogiPosted Oct 10, 2012, 11:20 PM
nice article.....
Varesh TuliPosted Oct 10, 2012, 11:08 PM
Nice article to understands lambda. Thanks for sharing.
Gaurav GuptaPosted Oct 10, 2012, 10:57 PM
Good article for learn about Lambda. But can you show how to use Lambda experession with DataTable object.