Función personalizada Y () para expresiones Linq

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.

En lugar de escribir

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.

preguntado el 01 de febrero de 12 a las 14:02

So... you want your code to look like vb? -

3 Respuestas

Well without cualquier extra work you can use:

Products.Where(OnSale).Where(Blue).Where(InStock);

... Where calls naturally compose as "And". Alternatively, PredicateBuilder makes it pretty simple:

Products.Where(OnSale.And(Blue).And(InStock));

This just needs PredicateBuilder to be available with a suitable using directive to pick up its extension methods.

Respondido 01 Feb 12, 18:02

Thank you - this is exactly what I wanted to do, but couldn't figure out the syntax. - powlette

The easiest solution would be to just chain the calls to Where():

Products.Where(OnSale).Where(Blue).Where(InStock);

Respondido 01 Feb 12, 18:02

Tuyo .And() es exactamente igual que .Where() (at least in Linq-to-objects).

Puedes escribir:

Productis.Where(p=>p.IsOnSale)
            .Where(p=.p.Color = Color.Blue)
            .Where(p=>p.Quality > 0);

Respondido 01 Feb 12, 18:02

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.