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:
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:
![Lamba-Expression1.jpg]()
- The following code checks any person's age that is between 13 and 19 years:
![Lamba-Exp2.jpg]()
- The following code checks whether all the people's ages are greater than Ten years or not:
![Lamba-Exp3.jpg]()
- The following code gets the average of all the people's ages:
![Lamba-Exp4.jpg]()
- The following code checks whether a person having the name 'SAM' exists or not:
![Lamba-Exp5.jpg]()
- The following code checks at what position a person having the name 'Smith' exists in the list:
![Lamba-Exp7.jpg]()
- The following code retrieves the oldest person in the list:
![Lamba-Exp7.jpg]()
- The following code gets the total of all the people's ages:
![Lamba-Exp8.jpg]()
- The following code skips each person whose age is less than 60:
![Lamba-Exp9.jpg]()
- The following code retrieves all the people until we find a person with a name beginning with any letter other than "S" :
![Lamba-Exp10.jpg]()
- The following code checks whether all the people have their SSN or not:
![Lamba-Exp11.jpg]()
- The following code removes all the people having the name "SAM":
![Lamba-Exp12.jpg]()
- The following code searches for the person having "203456876" as their SSN:
![Lamba-Exp13.jpg]()