Tuesday, August 23, 2005

Searching Generic Collections

When you find something it is always in the last place you were searching for it. Searching through generic collections using anonymous delegates however has never been as much fun. Consider a list of type Person, now take a look at the following line of code:

List<Person> youngPersons = persons.FindAll(YoungerThan(18));

Now this is what I call self explaining code without being too specific.

The YoungerThan function returns a predicate that will test an item in the collection and returns a Boolean value indicating the truth of the predicate. It is very cool that the predicate delegate can be parameterized, for instance in the YoungerThan implementation:

private Predicate<Person> YoungerThan(int age)
{
     Predicate<Person> youngerThan = delegate(Person person)
     {
          return person.Age < age;
     };

     return youngerThan;
}

The function can either be implemented in the class in which you use it or as part of the class to be searched. In the latter case you would probably implement it as a static function.

Comments: Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?