简体   繁体   中英

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.

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.

Example:

person A is mapped to category 1, category 2 and catgory 3 person B is mapped to category 1 and catgory 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.

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. And data is either an IQueryable.

Any idea how I can build this query?

T

Edit: This is not valid LINQ to SQL, but LINQ to Objects. May help as a source of inspiration anyway.

You could work with the Intersect method :

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 .

Howsaboutthis? Mudu beat me to it with the exact same solution, so this is my alternative.

Only select objects from data if all the elements in the catIDs list satisfy the condition, that p.CategoryMappings must contain the element.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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