OdeToCode IC Logo

Generics and Predicates

Saturday, July 10, 2004
What will be an elegant technique to remove objects matching a condition from a List in C# 2.0?

If the following code finds a match, we’ll find out it’s a no-no.

foreach (string s in list)
{
    if (s == "two")
        list.Remove(s);
}

In VS2005, the code creates this friendly little dialog.

C# 2.0 introduces generics, and with generics come predicates. A predicate returns true when an object meets a set of conditions, otherwise false. A method like List.RemoveAll will run each object in the collection through a given predicate to test each object for a match. When the predicate returns true, the method removes the object from the collection. The nifty thing is, you can write the predicate as an anonymous delegate:

list.RemoveAll(
    delegate(string s)  { return s == "Two"; }
);
 

Alternatively, you can keep your logic inside a named method.

static bool MatchTwoPredicate(string s)
{
    if (s == "Two")
        return true;
    return false;
}

// and later . . . 
 
list.RemoveAll(MatchTwoPredicate);

I feel either technique is easier on the eyes when compared to STL and functors in C++. Then again, I should be sleeping right now instead of blogging.