Home > Articles > Programming > C#

  • Print
  • + Share This
Like this article? We recommend

Searching a Generic Collection

To search a collection, I use what's called a predicate; that is, a delegate type for a method. This is simply a method that carries out the required search by using a supplied set of criteria. Depending on the criteria, the method returns either true or false. Listing 13 contains an example of a simple predicate.

Listing 13 A predicate method.

private static bool AnotherEmployee(Person p) 
{
  if (p.Name.Equals("Another Employee"))
  {
   Console.WriteLine("Managed to locate: " + "Another Employee");
   return true;
 }
 else
 {
   return false;
 }

The method in Listing 13 simply checks the name of the Person object passed into it and returns a Boolean value. Each element of the collection is passed into the search method until a match is found. This process probably sounds much more complicated than it is! The following single line of code invokes the Listing 13 method:

genericCollection.MyGenericCollection.Find(AnotherEmployee);

Notice that the delegate name is simply passed into the Find() method. Listing 14 holds the program output.

Listing 14 Program output indicating the successful collection search.

Collection capacity: 0
Person called: An Employee
Person called: A Contractor
Person called: Another Employee
Number of entries: 3
Name is An Employee
Name is A Contractor
Name is Another Employee

Sorted name is A Contractor
Sorted name is An Employee
Sorted name is Another Employee
Managed to locate: Another Employee

Notice the end of Listing 14 that the code has searched the generic collection and located the required element.

  • + Share This
  • 🔖 Save To Your Account