Thursday, April 24, 2008

Predicate Delegate

To pose a problem, let's create a strongly typed list of the Person class:
public class Person
{
    public string FirstName { get; set; }
}

// ...

List<Person> people = new List<Person>
              {
                  new Person("Mark"),
                  new Person("Rod"),
                  new Person("Matt"),
                  new Person("Rich"),
                  new Person("Jake")
              };
I used a collection initializer to populate a new typed generic List.

Ok, so how would you do a search in that collection and return the Person class that represents "Rod"? Luckily this generic list class has 5 different Find type methods (9 if you count the overloads).

Take a look at them though. They take a "Predicate". What the heck is this "Predicate"?

The word "predicate" is a term used in the subject of Logic that basically means
"to say something is true or false"
.

A predicate in .NET is a delegate that represents a method you write to check if a condition is true or false. So your predicate method will take in one parameter, evaluate it, and then return a true or false. Let's see what this might look like:
// Your predicate function.
private bool FindRod(Person person)
{
    if (person.FirstName == "Rod")
        return true;
    return false;
}

// ...

Person foundPerson = people.Find(FindRod);
Now when you call the Find method, just pass in the name of your predicate method. The Find method will loop through all the items in the collection and run your predicate method until a true is returned.

Now that you have the basics down, I think you can take a look at the other Find methods and be able to tell what they do.

More Info: MSDN: Predicate(T) Generic Delegate