Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add 'where' clausures dynamically to linq query

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

.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

>Solution :

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)
....
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading