Entity Framework multiple Where statements like ORs

Edit - using IQueryable, not in memory collection.

Therefore, I mainly want to use Where clauses based on some flags, but not use them as AND. So let me say that I need results where "Foo" is true, or "Bar" is true. I'm doing it now ...

results = results.Where(r => r.Foo || r.Bar);

which is good, but there are many conditions in which I need to add ORs, and if I could bind them together, that would make the code more readable.

Is there an EASY way to do this, 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 really doesn’t cost me if I need to create Expression objects and the like, or use a third-party library, it’s just interesting if there was something simple that I didn’t see.

, Union(), , , ( ).

, . - . , "". , , -, .

+4
1

PredicateBuilder. http://www.albahari.com/nutshell/predicatebuilder.aspx

, :

Expression<...> filter = PredicateBuilder.False();
if (something)
    filter = filter.Or(r => r.Foo);
if (somethingElse)
    filter = filter.Or(r => r.Bar);
return results.Where(filter);

, :

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... 
+7

Source: https://habr.com/ru/post/1546894/


All Articles