mo.notono.us

Tuesday, November 20, 2007

C#: An actual use for a Predicate

I love the List<T> class in C#2.0+, but haven't really used it much beyond as a typed ArrayList.  It's normally plenty.

But today I was building a dynamic CAML string and started doing a bunch of repetitive code like

List clauses = new List();

string foo = GetFooClause();
if (!string.IsNullOrEmpty(foo))
   clauses.Add(foo);

string bar = GetBarClause();
if (!string.IsNullOrEmpty(bar))
   clauses.Add(bar);

//..
when I realized there was a much simpler way:
List clauses = new List();

clauses.Add(GetFooClause());
clauses.Add(GetBarClause());
//...			

//remove all empty clauses
clauses.RemoveAll(string.IsNullOrEmpty);

The last line is the kicker - List.RemoveAll() takes a Predicate (i.e. a functor with a single parameter) - and String.IsNullOrEmpty() happens to be just the Predicate for the job.

Labels: ,

0 Comments:

Post a Comment

Links to this post:

Create a Link

<< Home