Find a specific value within a generic list using C#

It is common to have a need to search though a generic list to know if it contains a specific value. This is where the Find() method can be used.

There are many different scenarios you may encounter for searching, I will cover 2 here. The first is searching a list which contains a Class and another which contains a String.

public static List<currency> FindItClass = new List<currency>();
public static List<string> FindIt = new List<string>();
public class Currency
{
    public string Country { get; set; }
    public string Code { get; set; }
}

After populating both lists with data (you can see how to do this in the source code below) I use the Find() method to search for the specified value.

Currency result = 
    FindItClass.Find(delegate(Currency cur) 
           { return cur.Code == searchFor; });

As you can see, I create a delegate of the Currency calls called cur. Then, I search for a Code based on the user requested value stored in the searchFor variable. The result of this search will be an instance of the Currency class and will be NULL if nothing was found.

Searching for a string is very similar. I create a string delegate and search all the strings within the list, just like I did for a class.

string stringResult = 
    FindIt.Find(delegate(string str) 
            { return str == searchFor; });

Like I always like to mention, avoid writing additional code that does the same things that are already provided within the List Class. It is possible to perform the same type of action and get the same result using a for, while or foreach loop, but this would be wrong and bad practice. Study the .Net framework and the classes provided there, you will be surprised at how much work is already done for you.

Download the source.

Check out my other post where you can achieve the same thing but using Lambda Expressions here.




Leave a Comment

Your email address will not be published.