Edit - using IQueryable, not an in memory collection.
So I basically want to tack on Where clauses based on some flags, but not have them act as ANDs. So let's say I want results where "Foo" is true Or "Bar" is true. I'm currently doing this...
results = results.Where(r => r.Foo || r.Bar);
which is fine, but there's a lot of conditions that I need to add ORs to and if I could chain them after each other it would make the code much more readable.
Is there any SIMPLE way to do it like the following, but using OR instead of AND.
if (something)
results = results.Where(r => r.Foo)
if (somethingElse)
results = results.Where(r => r.Bar)
It's not really worth it to me if I have to build Expression objects and stuff like that, or use a 3rd party library, just wondering if there was something simple I wasn't seeing.
Also, I thought about using Union()
, but it seemed to perform slower(although it was more readable).
Some more info that could help. Basically my conditions are user roles. And they can be in any combination of roles, but each one should add an OR condition to the "results". So yeah, the enum flag thing that someone mentioned could help here.
Use PredicateBuilder. http://www.albahari.com/nutshell/predicatebuilder.aspx
It's a dozen lines and it lets you do this:
Expression<...> filter = PredicateBuilder.False();
if (something)
filter = filter.Or(r => r.Foo);
if (somethingElse)
filter = filter.Or(r => r.Bar);
return results.Where(filter);
This gives you all the same performance benefits as if you had written:
if (something && somethingElse)
return results.Where(r => r.Foo || r => r.Bar)
else if (something)
return results.Where(r => r.foo)
else if (somethingElse)
return results.Where(r => r.Bar)
etc...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With