如何在 linq 中检索标有所有提供的标签的项目?

How do I retrieve items that are tagged with all the supplied tags in linq?(如何在 linq 中检索标有所有提供的标签的项目?)
本文介绍了如何在 linq 中检索标有所有提供的标签的项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我似乎遇到了这个问题.我有一个带有 ID 的任务表和一个标签表,它有一个标签字段和一个到任务表的外键约束.

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.

我希望能够通过标签对任务执行 AND 搜索.例如,如果我搜索带有可移植性"和测试"标签的任务,我不想要带有可移植性"而不是测试"标签的任务.

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

我尝试了以下语法:

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

这当然是 OR 搜索,而不是 AND 搜索.我不知道如何将其实际切换为 AND 搜索.

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.

编辑我还需要能够搜索任务包含的 X 个标签中的 2 个.因此,如果任务被标记为错误修复"、可移植性"、测试"并且我搜索测试"和可移植性",该任务仍会显示.

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.

推荐答案

你想做的这个

LinqToSql 可能看起来像:

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

我还没有测试过这个,Distinct 位可能有点差.检查生成的 sql 以确保.

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

这篇关于如何在 linq 中检索标有所有提供的标签的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Is Unpivot (Not Pivot) functionality available in Linq to SQL? How?(Linq to SQL 中是否提供 Unpivot(非 Pivot)功能?如何?)
How to know if a field is numeric in Linq To SQL(如何在 Linq To SQL 中知道字段是否为数字)
Linq2SQl eager load with multiple DataLoadOptions(具有多个 DataLoadOptions 的 Linq2SQl 急切加载)
Extract sql query from LINQ expressions(从 LINQ 表达式中提取 sql 查询)
LINQ Where in collection clause(LINQ Where in collection 子句)
Orderby() not ordering numbers correctly c#(Orderby() 没有正确排序数字 c#)