0

I'm looking for a way to chain multiple OR clauses in a EF query.

Here's an example function, which, when called with an argument int[] containing exactly 2 elements, will create an OR clause with them (of course, less than 2 elements would cause an exception and more than 2 elements would be ignored):

public async Task<List<MyTable>> MyQuery(DbContext dbContext, int[] list)
{
    IQueryable<MyTable> q = dbContext.MyTable;

    q = q.Where(x => x.Id == list[0] || x.Id == list[1]);

    // here I chain several other clauses...
    q = q.Where(x => x.SomeOtherFiled == 123);

    return  await q.ToListAsync();
}

I would like to modify this code in a way that would perform OR logic with all the elements of the array (1-n; ie. any length). In this example I'm using an int data type, but in reality it could be any data type that can exist in a EF data set. Several AND conditions could be chained together (here I use SomeOtherFiled as an example). I hope I explained well the problem.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Marko
  • 1,502
  • 5
  • 21
  • 40
  • Does this answer your question? [How to chain alternative conditions in where clause in Entity Framework](https://stackoverflow.com/questions/17395417/how-to-chain-alternative-conditions-in-where-clause-in-entity-framework) – Igor Sep 16 '21 at 19:11
  • Does this answer your question? [Dynamic query with OR conditions in Entity Framework](https://stackoverflow.com/a/20055137/1260204) – Igor Sep 16 '21 at 19:12
  • I took a look at LinqKit, but it seems a pretty complicated subject, and the examples are not very helpful. Thanks anyway. – Marko Sep 17 '21 at 19:05

1 Answers1

1

It sounds like what you are describing is equivalent to the IN operator in SQL (ex: WHERE Id IN (1,4,6)).

The equivalent Linq is like this:

int[] list = {1,4,6};
q = q.Where(x => list.Contains(x.Id))
Neal Burns
  • 839
  • 4
  • 5