Using a Lambda Expression Over a List in C#

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:
  1. class Person  
  2. {  
  3.     public string SSN;  
  4.     public string Name;  
  5.     public string Address;  
  6.     public int Age;  
  7.     public Person(string ssn, string name, string addr, int age)  
  8.     {  
  9.         SSN = ssn;  
  10.         Name = name;  
  11.         Address = addr;  
  12.         Age = age;  
  13.     }  
  14. }  
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:
  1. List<Person> listPersonsInCity = new List<Person>();  
  2. listPersonsInCity.Add(new Person("203456876""John""12 Main Street, Newyork, NY", 15));  
  3. listPersonsInCity.Add(new Person("203456877""SAM""13 Main Ct, Newyork, NY", 25));  
  4. listPersonsInCity.Add(new Person("203456878""Elan""14 Main Street, Newyork, NY", 35));  
  5. listPersonsInCity.Add(new Person("203456879""Smith""12 Main Street, Newyork, NY", 45));  
  6. listPersonsInCity.Add(new Person("203456880""SAM""345 Main Ave, Dayton, OH", 55));  
  7. listPersonsInCity.Add(new Person("203456881""Sue""32 Cranbrook Rd, Newyork, NY", 65));  
  8. listPersonsInCity.Add(new Person("203456882""Winston""1208 Alex St, Newyork, NY", 65));  
  9. listPersonsInCity.Add(new Person("203456883""Mac""126 Province Ave, Baltimore, NY", 85));  
  10. 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. 
  1. The following code retrieves the first two persons from the list who are older than 60 years: 
    1. Console.WriteLine("\n-----------------------------------------------------------------------------");  
    2. Console.WriteLine("Retrieving Top 2 aged persons from the list who are older than 60 years\n");  
    3. foreach (Person person in listPersonsInCity.FindAll(e => (e.Age >= 60)).Take(2).ToList())  
    4. {  
    5.     Console.WriteLine("Name : " + person.Name + " \t\tAge: " + person.Age);  
    6. }
    Lamba-Expression1.jpg

  2. The following code checks any person's age that is between 13 and 19 years: 
    1. Console.WriteLine("\nChecking whether any person is teen-ager or not...");  
    2. if (listPersonsInCity.Any(e => (e.Age >= 13 && e.Age <= 19)))  
    3. {  
    4.     Console.WriteLine("Yes, we have some teen-agers in the list");  
    5. }
    Lamba-Exp2.jpg

  3. The following code checks whether all the people's ages are greater than Ten years or not:
    1. Console.WriteLine("\nCheking whether all the persons are older than 10 years or not...");  
    2. if ( listPersonsInCity.All(e => (e.Age > 10)))  
    3. {  
    4.     Console.WriteLine("Yes, all the persons older than 10 years");  
    5. }
    Lamba-Exp3.jpg

  4. The following code gets the average of all the people's ages:
    1. Console.WriteLine("\nGetting Average of all the person's age...");  
    2. double avgAge = listPersonsInCity.Average(e => e.Age);  
    3. Console.WriteLine("The average of all the person's age is: "+ avgAge);
    Lamba-Exp4.jpg

  5. The following code checks whether a person having the name 'SAM' exists or not:
    1. Console.WriteLine("\nChecking whether a person having name 'SAM' exists or not...");  
    2. if (listPersonsInCity.Exists(e => e.Name == "SAM"))  
    3. {  
    4.     Console.WriteLine("Yes, A person having name  'SAM' exists in our list");  
    5. }
    Lamba-Exp5.jpg

  6. The following code checks at what position a person having the name 'Smith' exists in the list:
    1. Console.WriteLine("\nChecking the index position of a person having name 'Smith' ...");  
    2. int indexForSmith = listPersonsInCity.FindIndex(e => e.Name == "Smith");  
    3. Console.WriteLine("In the list, The index position of a person having name 'Smith' is : " + indexForSmith);
    Lamba-Exp7.jpg

  7. The following code retrieves the oldest person in the list:
    1. Console.WriteLine("\nGetting the name of the most aged person in the list ...");  
    2. Person p = listPersonsInCity.First(m=> m.Age == (listPersonsInCity.Max(e => e.Age)));  
    3. Console.WriteLine("The most aged person in our list is: "+ p.Name +" whose age is: "+ p.Age);
    Lamba-Exp7.jpg

  8. The following code gets the total of all the people's ages:
    1. Console.WriteLine("\nGetting Sum of all the person's age...");  
    2. int sumOfAges = listPersonsInCity.Sum(e => e.Age);  
    3. Console.WriteLine("The sum of all the persons's age = "+ sumOfAges);
    Lamba-Exp8.jpg

  9. The following code skips each person whose age is less than 60:
    1. Console.WriteLine("\nSkipping every person whose age is less than 60 years...");  
    2. foreach (Person pers in listPersonsInCity.SkipWhile(e => e.Age < 60))  
    3. {  
    4. Console.WriteLine("Name : "+ pers.Name + " \t\tAge: "+ pers.Age);  
    5. }
    Lamba-Exp9.jpg

  10. The following code retrieves all the people until we find a person with a name beginning with any letter other than "S" :
    1. Console.WriteLine("Displaying the persons until we find a person with name starts with other than 'S'");  
    2. foreach (Person pers in listPersonsInCity.TakeWhile(e => e.Name.StartsWith("J")))  
    3. {  
    4.     Console.WriteLine("Name : " + pers.Name + " \t\tAge: " + pers.Age);  
    5. }
    Lamba-Exp10.jpg

  11. The following code checks whether all the people have their SSN or not:
    1. Console.WriteLine("\nChecking all the persons have SSN or not ...");  
    2. if(listPersonsInCity.TrueForAll(e => e.SSN != null))  
    3. {  
    4.     Console.WriteLine("No person is found without SSN");  
    5. }
    Lamba-Exp11.jpg

  12. The following code removes all the people having the name "SAM":
    1. Console.WriteLine("\nRemoving all the persons record from list that have "SAM" name");  
    2. listPersonsInCity.RemoveAll(e => (e.Name == "SAM"));  
    3. if (listPersonsInCity.TrueForAll(e => e.Name != "SAM"))  
    4. {  
    5.     Console.WriteLine("No person is found with 'SAM' name in current list");  
    6. }
    Lamba-Exp12.jpg

  13. The following code searches for the person having "203456876" as their SSN:
    1. Console.WriteLine("\nFinding the person whose SSN = 203456876 in the list");  
    2. Person oPerson = listPersonsInCity.Find(e => (e.SSN == "203456876"));  
    3. Console.WriteLine("The person having SSN '203456876' is : " + oPerson.Name + " \t\tAge: " + oPerson.Age);
    Lamba-Exp13.jpg