Tuesday, August 7, 2012

Querying a List by Lambda Expression

Suppose you have a class “Person” and a list “lstPersonsInCity” is a collection of persons in a city as following:

Class Person
{
Public string SSN;
public string Name;
public string Address
public int Age;
}

List<Person> lstPersonsInCity = new List<Person>();


Now you can do perform several types of queries in your list by using lambda expression in a very easy way. Some examples are shown below:

  • // Grab Top 1000 old aged persons from the all the persons in city
List<Person> lstAgedPersonsInCity = lstPersonsInCity.FindAll(e =>
(e.Age >= 60)).Take(1000).ToList();

  • // Remove all the persons record from list that have “SAM” name
lstPersonsInCity.RemoveAll(e => (e.Name == “SAM”));

  • // Find the person whose SSN = 203456876 from the all the persons in city
Person oPerson = lstPersonsInCity.Find(e => (e.SSN == “203456876”));

No comments:

Post a Comment