How do I retrieve items that are tagged with all the supplied tags in linq?

一笑奈何 提交于 2019-11-28 14:26:03
Amy B

You want to do this

the LinqToSql might look like:

List<int> myTags = GetTagIds();
int tagCount = myTags.Count;

IQueryable<int> subquery =
  from tag in myDC.Tags
  where myTags.Contains(tag.TagId)
  group tag.TagId by tag.ContentId into g
  where g.Distinct().Count() == tagCount
  select g.Key;

IQueryable<Content> query = myDC.Contents
  .Where(c => subQuery.Contains(c.ContentId));

I haven't tested this and the Distinct bit might be off a little. Check the generated sql to be sure.

Use All instead of Any; and in order to only select the KnowledgeBaseTasks, that has all the tags (but possibly more); reverse the expression:

var tasks = (from t in _context.KnowledgeBaseTasks
                 where tags.All(tag => t.KnowledgeBaseTaskTags.Contains(tag))
                 select KnowledgeBaseTaskViewModel.ConvertFromEntity(t)
                ).ToList();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!