I have a collection of data points in a custom class. I also have many different conditions that I need to test for in different combinations all over my application and I want to define those conditions as Expressions. Let’s say my collection has Products.
Instead of writing
Products.Where(p => p.IsOnSale && p.Color == Color.Blue && p.Quality > 0);
what I’d like to be able to do, for clarity is to define the predicates in one place:
Expression<Func<Product, bool>> OnSale = (p) => p.IsOnSale;
Expression<Func<Product, bool>> Blue = (p) => p.Color = Color.Blue;
Expression<Func<Product, bool>> InStock = (p) => p.Quantity > 0;
....
and then filter my collections using these predicates:
Products.Where(OnSale).And(Blue).And(InStock);
or
Products.And(OnSale, Blue, InStock);
So I can easily see what I’m returning, I only define the conditions once, and if any of the conditions change, I can just update the predicates rather than every place I’m doing a Where().
How can I accomplish this? I looked at PredicateBuilder but Linq.Expressions is totally new to me.
Well without any extra work you can use:
…
Wherecalls naturally compose as “And”. Alternatively,PredicateBuildermakes it pretty simple:This just needs
PredicateBuilderto be available with a suitable using directive to pick up its extension methods.