Is there any way in c# .NET 2.0! to combine multiple Predicates?
Let\'s say I have the following code.
List names = new List
How about:
public static Predicate Or(params Predicate[] predicates)
{
return delegate (T item)
{
foreach (Predicate predicate in predicates)
{
if (predicate(item))
{
return true;
}
}
return false;
};
}
And for completeness:
public static Predicate And(params Predicate[] predicates)
{
return delegate (T item)
{
foreach (Predicate predicate in predicates)
{
if (!predicate(item))
{
return false;
}
}
return true;
};
}
Then call it with:
List filteredNames = names.FindAll(Helpers.Or(StartsWithE, StartsWithI));
Another alternative would be to use multicast delegates and then split them using GetInvocationList(), then do the same thing. Then you could do:
List filteredNames = names.FindAll(Helpers.Or(StartsWithE+StartsWithI));
I'm not a huge fan of the latter approach though - it feels like a bit of an abuse of multicasting.