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.


Comments
Scott Allen Friday, July 16, 2004
Ooops! Scott found a bug. I was obviously half asleep and careless: http://ea.3leaf.com/2004/07/generics_and_pr.html
<br>Updated.
gravatar sithara Wednesday, December 9, 2009
what is Predicative genetics?
Comments are now closed.
by K. Scott Allen K.Scott Allen
My Pluralsight Courses
The Podcast!