简体   繁体   English

Linq to Sql选择具有多个id之一的映射项

[英]Linq to Sql select mapping items with one of many id's

Having brain-lock and need a simple/quick answer - I am probably looking at this from the wrong end, but I have a lot on my plate this week. 有脑力锁定并需要一个简单/快速的答案 - 我可能从错误的一端看这个,但本周我的盘子里有很多。 :-( :-(

Using linq-to-sql, I have a table with items mapped to many categories via a mapping table. 使用linq-to-sql,我有一个表,其中的项目通过映射表映射到许多类别。

I now need to pull out all items which are mapped to multiple categories, but only items which are mapped to ALL the categories required. 我现在需要提取所有映射到多个类别的项目,但只显示映射到所需类别的所有项目。 This is a change to the original brief which was to pull data which is mapped to any category id. 这是对原始摘要的更改,该摘要用于提取映射到任何类别ID的数据。

Example: 例:

person A is mapped to category 1, category 2 and catgory 3 person B is mapped to category 1 and catgory 3 人A被映射到类别1,类别2,而目标3人B被映射到类别1和第3类

So if I select category 1 & 2 both person items are returned, however if I selected 1, 2 & 3 only person A should be returned. 因此,如果我选择类别1和2,则返回两个人物品,但是如果我选择1,2和3,则只返回人物A.

Here is the original (simplified) code which returns ANY item: 这是返回任何项目的原始(简化)代码:

IList<Person> results = (from a in data from b in a.CategoryMappings 
                   where catIDs.AsEnumerable().Contains(b.CategoryID) 
                   select a).Distinct().ToList();

catIDs is an IList<int> taken from the data sent to the query, this can be of any length. catIDs是从发送给查询的数据中取出的IList<int> ,可以是任意长度。 And data is either an IQueryable. 数据要么是IQueryable。

Any idea how I can build this query? 知道如何构建此查询吗?

T Ť

Edit: This is not valid LINQ to SQL, but LINQ to Objects. 编辑:这不是LINQ to SQL的有效,而是LINQ to Objects。 May help as a source of inspiration anyway. 无论如何,可能有助于作为灵感来源。

You could work with the Intersect method : 您可以使用Intersect方法

var results = (from a in data
               where catIDs.Intersect(a.CategoryMappings).Count() == catIDs.Count
               select a).Distinct().ToList();

It returns the intersection of both enumerabled, which should basically be as long as catIDs . 它返回两个enumerabled的交集,它应该基本上和catIDs一样长。

Howsaboutthis? Howsaboutthis? Mudu beat me to it with the exact same solution, so this is my alternative. Mudu用完全相同的解决方案打败了我,所以这是我的选择。

Only select objects from data if all the elements in the catIDs list satisfy the condition, that p.CategoryMappings must contain the element. 如果catIDs列表中的所有元素都满足条件,则只从数据中选择对象,p.CategoryMappings必须包含该元素。

var results = from p in data 
              where catIds.All(i => p.CategoryMappings.Contains(i))
              select p;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM