Searching a generic List collection using C#

Before you begin loading and populating collections, you should decide which collection to use based on the requirements. Some collections are built for speed when selecting, some are built for speed when loading, other for sorting, etc. A good description can be found here.

This example I will search a strongly typed List for a specific person. The first thing to do is created the class to search through.

public class Person
{
     public int Id { get; set; }
     public string Name { get; set; }
     public int Age { get; set; }
}

Second, load the Person class with data and load the list with the class.

List<Person> pList = new List<Person>()
{
     new Person() { Id = 0, Name = "Jens", Age = 20 },
     new Person() { Id = 1, Name = "Wolfgang", Age = 30 },
     new Person() { Id = 2, Name = "Albert", Age = 22 },
     new Person() { Id = 3, Name = "Andrea", Age = 19 },
     new Person() { Id = 4, Name = "Donna", Age = 23 },
     new Person() { Id = 5, Name = "Mary", Age = 32 },
     new Person() { Id = 6, Name = "Rick", Age = 14 },
     new Person() { Id = 7, Name = "Charles", Age = 34 },
     new Person() { Id = 8, Name = "RB", Age = 55 },
     new Person() { Id = 9, Name = "Todd", Age = 31 }
};

Let’s say for example I bind this List to a datagrid and when the row is selected I want to display all the details in a form that allows the data to be modified and save to a database. When the row is selected in the datagrid, assuming all data is not displayed in the datagrid, I would want to access the List, search for the ID and populate the form with the Name and Age so they can be viewed and possibly modified.

To search through the List I use the Find() method passing a delegate with the class I am searching.

Person p = pList.Find(delegate(Person _p)
{
     if (_p.Id == Identity)
     {
         Console.WriteLine("The person with Id = " +
                              Identity.ToString() +
                           " is " + _p.Name +
                           " and is " + _p.Age.ToString() +
                           " years old.");
         return true;
     }
 
     return false;
});

I captured the Identity from user input and display the Name and Age of the matching Person. I like this technique and it does rely on the uniqueness of the Id. If 2 People have the same Id, only the first will be returned.

Download the source