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

大城市里の小女人 提交于 2019-11-27 08:43:58

问题


I seem to be having trouble with this. I have a Task table with an ID, and a Tag table, that has a tag field and a foreign key constraint to the task table.

I want to be able to perform AND searches for tasks by tags. So for example, if I search for tasks with the tags "portability" and "testing", I don't want tasks that are tagged with "portability" and not "testing".

I tried the following syntax:

 var tasks = (from t in _context.KnowledgeBaseTasks
                     where t.KnowledgeBaseTaskTags.Any(x => tags.Contains(x.tag))
                     select KnowledgeBaseTaskViewModel.ConvertFromEntity(t)
                    ).ToList();

This of course does an OR search, not an AND search. I can't figure out how to actually switch this to be an AND search.

Edit I also need to be able to search for 2 out of X tags that a task contains. So if the task is tagged with "bugfix", "portability", "testing" and I search for "testing" and "portability", that task will still show up.


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/3478874/how-do-i-retrieve-items-that-are-tagged-with-all-the-supplied-tags-in-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!