Wednesday, 15 August 2007

Simple anonymous delegate II - Predicate

Follow from the previous post, anonymous delegate can be used as predicate, which is a method that defines a set of criteria and determines whether the specified object meets those criteria. For example we have the following method:

public static void DoSomething<TObj>(IEnumerable<TObj>
objs, Action<TObj> action, Predicate<TObj> pred)
{

foreach (TObj obj in objs)
if(pred(obj))
action(obj);

}


which takes a predicate parameter and only perform the action if the predicates is true.

We can pass in anonymous delegate for the predicate:
List<string> listOfStrings = new List<string>();
listOfStrings.Add("one");
listOfStrings.Add("two");
listOfStrings.Add("three");

AnonymousDelegate.DoSomething<string>(listOfStrings,
delegate(string s) { Response.Write(s + "<br/>");},
delegate(string s) { return !s.StartsWith("o"); });

In this case on "two" and "three" would be written out.

No comments:

Post a Comment