Predicates with .NET 2.0
In a previous blog entry I've shown the transformation of the Accumulate method from a traditional implementation to a generic implementation where the action is passed. This was the result of the last version that does something to every object in a collection:
public static TSum Accumulate<TObj, TSum>(
IEnumerable<TObj> coll, Action<TObj, TSum> action)
{
TSum sum = default(TSum);
foreach (TObj obj in coll)
{
sum = action(obj, sum);
}
return sum;
}
And this is how this method can be invoked with an anonymous delegate:
decimal amount = Algorithm.Accumulate<Account, decimal>(
accounts,
delegate(Account a, decimal sum)
{
return a.Balance + sum;
});
Now I'm extending the implementation of the Accumulate method by using a predicate. A predicate is a method that returns a boolean value. .NET 2.0 defines this generic predicate delegate:
public delegate bool Predicate<T>(T obj);
Such a predicate can be used with the AccumulateIf method to only work with these objects of a collection where the predicate returns true:
public static TSum AccumulateIf<TObj, TSum>(
IEnumerable<TObj> coll,
Action<TObj, TSum> action
Predicate<TObj> filter)
{
TSum sum = default(TSum);
foreach (TObj obj in coll)
{
if (filter(obj))
sum = action(obj, sum);
}
return sum;
}
Now the predicate implementation - the algorithm when the accumulation should happen - can be passed with the method AccumulateIf as anonymous method. In the example the action only happens if the balance has a value greater than 2500.
decimal amount = Algorithm.AccumulateIf<Account, decimal>(
accounts,
delegate(Account a, decimal sum) // Action
{
return a.Balance + sum;
},
delegate (Account a) // Predicate
{
return a.Balance > 2500;
}
);
Christian