Search in Generic List<T> in C#
Sometimes, we will have requirements to search for an object in a Generic List<T>.
For example, List<Customer> collection will have a collection of Customer objects. To a search a Customer object from collection we can use the new feature called Predicate delegate.
The below code snippet will search the customer based on a ID and returns that Customer object from the Collection.
List<Customer> cuslist1 = new List<Customer>();
Customer cus1 = new Customer();
cus1.ID = 1;
cus1.Name = "Fatima";
cus1.Age = 23;
cuslist1.Add(cus1);
Customer cus2 = new Customer();
cus2.ID = 2;
cus2.Name = "Evangeline";
cus2.Age = 24;
cuslist1.Add(cus2);
Customer cus3 = new Customer();
cus3.ID = 3;
cus3.Name = "Damien";
cus3.Age = 27;
cuslist1.Add(cus3);
Customer cus4 = new Customer();
cus4.ID = 4;
cus4.Name = "Cameroon";
cus4.Age = 21;
cuslist1.Add(cus4);
Customer cus5 = new Customer();
cus5.ID = 5;
cus5.Name = "Babu";
cus5.Age = 20;
cuslist1.Add(cus5);
Customer cusTemp = cuslist1.Find(delegate(Customer _cus)
{
if (_cus.ID == 4)
{
return true;
}
return false;
});
Response.Write(cusTemp.Name+"<br>"+cusTemp.Age);
In the above code, i have searched the customer with ID as 4. You can add your own filteration or criteria in the Find() method to find a object in generic list.
The above code uses Anonymous delegate. Follow the link to read more about Delegates and Anonymous methods in C#
|