Reputation: 5
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
Upvotes: 0
Views: 1034
Reputation: 578
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;
Upvotes: 0
Reputation: 12513
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
.
Upvotes: 2