Home > Enterprise >  Add 'where' clausures dynamically to linq query
Add 'where' clausures dynamically to linq query

Time:04-07

I have this linq query:

var query = (from dc in context.Table1.Include(d => d.Doc)
                         join u in _context.Table2 on dc.IDDoc equals u.IDDoc
                         where dc.ID == id && u.IDUser == user.IDUser
                         select dc)
                        .Union(from dc in context.Table1.Include(d => d.Doc)
                               join p in _context.Table3 on dc.IDDoc equals p.IDDoc
                               where dc.ID == id
                               select dc);

And I want to add more where conditions dynamically depends of a list (List ids) What I want to achieve is something like this:

Imagine that I have a List ids = new(){1, 2, 5, 27); What I want to do is to add that info into this part of the query to have something like this:

.Union(from dc in context.Table1.Include(d => d.Doc)
      join p in _context.Table3 on dc.IDDoc equals p.IDDoc
      where dc.ID == id && p.ID == 1 || p.ID == 2 || p.ID == 5 || p.ID = 27
      select dc)

But if next time list is List ids = new(){4}, query should look like:

.Union(from dc in context.Table1.Include(d => d.Doc)
          join p in _context.Table3 on dc.IDDoc equals p.IDDoc
          where dc.ID == id && p.ID == 4 
          select dc)

Is it even possible? If not, what would be a possible solution? Thank you

CodePudding user response:

Use Enumerable.Contains:

List<int> ids = new(){4};
....
   .Union(from dc in context.Table1.Include(d => d.Doc)
          join p in _context.Table3 on dc.IDDoc equals p.IDDoc
          where dc.ID == id && ids.Contains(p.ID) // here 
          select dc)
....
  • Related