通过标签选择项目搜索多个标签时, [英] Select items by tag when searching multiple tags

查看:319
本文介绍了通过标签选择项目搜索多个标签时,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我挣扎了一下这里,所以我想为什么不问:

I'm struggling a bit here so I thought why not ask:

在我的系统中每个实体都有标签列表(字符串列表),而我希望能够寻找多个标签一次。

Every entity in my system has a list of tags (a list of strings), and I want to be able to search for multiple tags at once.

我有一个IQueryable的一起工作。每个实体都有一个IList的所谓的标签,我的输入参数是一个IList中。

I have a IQueryable to work with. Every Entity has a IList called Tags and my input parameter is a IList.

我根本就通过所有的标签和做IQueryable.Where(P => p.Tags.Contains(currentTag),但不会规模非常好了许多标记作为输入,并且还我有一种感觉,这可能里面的LinQ来完成。

I simply could go through all tags and do IQueryable.Where(p => p.Tags.Contains(currentTag), but that would not scale very well with many tags as input, and also I have the feeling that this could be done inside LinQ.

希望任何人有一个想法。

Hope anyone has an Idea.

编辑:的问题澄清: 我搜索的方式,只选择从我的IQueryable包含所有提供的参数标签(IList中的)项目。

Clarification of question: I search for a way to only select Items from my IQueryable that contain ALL supplied parameter tags (of IList).

问候丹尼尔/ Tigraine

greetings Daniel / Tigraine

推荐答案

从<一个href="http://stackoverflow.com/questions/163887/sql-query-simulating-an-and-over-several-rows-instead-of-sub-querying#163907">here,这是一些SQL会为你工作:

From here, this is some sql that will work for you:

SELECT entityID
FROM tags
WHERE tagID in (...) --taglist
GROUP BY entityID
HAVING COUNT(DISTINCT tagID) = ... --tagcount

现在的关键问题是让LINQ到生产它...以下是一些LinqToSql code:

Now the trick is getting Linq to produce it... Here's some LinqToSql code:

public List<int> GetEntityIds(List<int> tagIds)
{
  int tagCount = tagIds.Count;

  CustomDataContext myDC = new CustomDataContext();

  List<int> entityIds = myDC.Tags
    .Where(t => tagIds.Contains(t.TagId))
    .GroupBy(t => t.entityId)
    .Where(g => g.Select(t => t.TagId).Distinct().Count() == tagCount)
    .Select(g => g.Key)

  return entityIds;
}

几个注意事项适用:

A few caveats apply:

  • 列表(T)。载由LinqToSql翻译,但LinqToEntities不会翻译它。实际上,您将得到一个运行时异常。
  • IList.Contains ......没有人翻译的。使用List(T)来代替。
  • 有一个在为SQL Server效果的参数数量限制。这是大约2000个参数(高,但比2500更低)。如果你需要使用超过2000个标签,你应该寻求不同的解决方案。
  • 在我写这篇无需工具,午夜后。它可能并不完美。

这篇关于通过标签选择项目搜索多个标签时,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆