动态添加 'where' 子句到 linq 查询

Add 'where' clausures dynamically to linq query

我有这个 linq 查询:

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);

而且我想在条件动态依赖于列表(列表 ID)的情况下添加更多内容 我想要实现的是这样的:

假设我有一个列表 ids = new(){1, 2, 5, 27); 我想要做的是将该信息添加到查询的这一部分中,以获得如下内容:

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

但是如果下一次列表是 List 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 && p.ID == 4 
          select dc)

这可能吗?如果没有,可能的解决方案是什么? 谢谢

编辑:我编造了这个查询,因为我不知道如何将它添加到我的主查询中。 我真正拥有的是:

var mainQuery = _context.RootTable
            .Include(i => i.Items).ThenInclude(dc => dc.Docs)
            .Include(i => i.Items).ThenInclude(sg => sg.Signs)
            .FirstOrDefault(m => m.ID== id);

我想做的是用另一个查询过滤“.ThenInclude(dc => dc.Docs)。我不知道如何以更好、更有效的方式做到这一点有两个单独的查询。

使用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)
....