Reputation: 6865
I have multiple expressions in a List.
var expressions = new List<Expression<Func<T, bool>>>() { .... };
I want to create an extension method to match them AND or OR logic.
public static class ExpressionExtension{
public static Expression<Func<T, bool>> And(this IList<Expression<Func<T, bool>>> exp){
// for all items with AND
}
public static Expression<Func<T, bool>> Or(this IList<Expression<Func<T, bool>>> exp){
// for all items with OR
}
}
How can I do this?
Upvotes: 0
Views: 81
Reputation: 134891
As a suggestion, I would reconsider how you name your extensions. They seem to correspond to the existing LINQ All()
and Any()
methods. You could add And()
and Or()
for single predicates, it would make a lot more sense.
Using predicate builder:
public static class ExpressionExtensions
{
public static Expression<Func<T, bool>> All<T>(this IEnumerable<Expression<Func<T, bool>>> source) =>
source.Aggregate(PredicateBuilder.True<T>(),
(acc, predicate) => acc.And(predicate) // And() provided by PredicateBuilder
);
public static Expression<Func<T, bool>> Any<T>(this IEnumerable<Expression<Func<T, bool>>> source) =>
source.Aggregate(PredicateBuilder.False<T>(),
(acc, predicate) => acc.Or(predicate) // Or() provided by PredicateBuilder
);
}
Upvotes: 1