0

I'm have a query with some "OR" operators. for instance.

entities.Where(e=> (...) || (...) || (...) || (...));

I would like to break this into several calls like the Where() function allows me. for instance:

entities = entities.Where(e => (some logic A));
// ...
entities = entities.Where(e => (some logic B));
// ...
entities = entities.Where(e => (some logic C));

Is possible to do the same but for a OR logic instead of AND Logic?

The main reason that I would like to break this logic into several lines of code is that each OR can be applied by different functions.

Daniel Santos
  • 14,328
  • 21
  • 91
  • 174

1 Answers1

2

you can do something like:

set1 = entities.Where(e => (some logic A));
set2 = entities.Where(e => (some logic B));
set3 = entities.Where(e => (some logic C));

entities = set1.Union(set2).Union(set3);
Amy B
  • 108,202
  • 21
  • 135
  • 185
  • 1
    wouldn't that be like 3 separated queries ? – Gonzalo.- May 29 '18 at 02:00
  • 3
    In LinqToObjects - yes, 3 enumerations of the source. In most other query providers - no, it would be a single union'd query. It's important to know that queries are not executed until enumerated (as happens in foreach or ToList) – Amy B May 29 '18 at 02:01
  • is this a most expensive query than regular "OR" in EntityFramework (SQL Server) ? – Daniel Santos May 29 '18 at 02:09
  • 1
    @DanielSantos - Profile it and find out. It's the only way to know. – Enigmativity May 29 '18 at 02:11
  • 1
    Depending on the underlying implementation, you might also need a `Distinct` call to avoid duplicates where one item matches multiple criteria. – jmcilhinney May 29 '18 at 02:25
  • No, there wouldn't be three separated queries. In fact, the code described only creates an IQueryable object. The IQueriable.Expression changes with each LINQ function, but no query is performed yet, The query is performed as soon as you really start enumerating. This is usually done by functions like ToList(), ToArray(), FirstOrDefault(), Max(), ... At that moment the IQueryable.Provider interprets the one and only IQueryable.Expression, which will lead to one database query (depending on the quality of the IQueryable.Provider). – Harald Coppoolse May 29 '18 at 06:26
  • @jmcilhinney: No; `.Union()` (unlike `.Concat()`) already does that. – SLaks May 29 '18 at 23:46
  • @SLaks, thanks. I see that the documentation says that so I should have looked first. – jmcilhinney May 30 '18 at 01:17