Reputation: 2687
I'm battling with what I thought would be a simple query...
Schema is like:
Documents
(DocumentID, Name)
Industries
(IndustryID, Name)
Documents_Industries
(DocumentID, IndustryID)
Data is like:
DocA -- IndustryA
DocB -- IndustryA, IndustryB
DocC -- IndustryA, IndustryB
DocD -- IndustryB
(So the data above would result in 6 rows in Documents_Industries
, hopefully that's self-explanatory)
Expected behaviour: I'm trying to show a list of Documents, filtered by the Industry(ies) a user selects. If IndustryA is selected, result set should be DocA, DocB, DocC. If IndustryB is selected, result set should be DocB, DocC, DocD. If IndustryA and IndustryB is selected, result set should be DocB, DocC.
Code so far:
IEnumerable<Document> docs = db.Documents.Where(l => l.IsActive == true);
// industryIdsSelected is an int[] from the user's selection
if (industryIdsSelected.Length > 0)
{
docs = docs.Where(l => l.Industries.Any(m => industryIdsSelected.Contains(m.IndustryID)));
}
Actual behaviour: If IndustryA and IndustryB is selected, result set is DocA, DocB, DocC, DocD. Instead of just DocB, DocC.
I've tried with .All()
but that doesn't work either. What could I be doing wrong?
Upvotes: 1
Views: 3631
Reputation: 26634
You need to use both All
and Any
like this:
docs.Where(l => industryIdsSelected.All(x => l.Industries.Any(m => m.IndustryID == x)));
Upvotes: 2