Reputation: 163
I need to search database users by tags. One user has many tags and one tag is shared by many users. But when I search by specific set of tags I want want users that have all these tags but can have tags that I do not search for ofc. Here were my tries:
return context.Contacts.Include("Tags").Where(c => c.Tags.**Any**(t => tagIds.Contains(t.Id.ToString()))).ToList();
//Above approach would search kind of union between tags. It would not converge. Meaning if I have user1 with tags A and B and user2 with B and C And I search by A and B i would get both users, even though i want only user1
//Bellow apporach would search too strict, meaning if user contains tags A and B and i search by tag A this user would not be showed
return context.Contacts.Include("Tags").Where(c => c.Tags.**All**(t => tagIds.Contains(t.Id.ToString()))).ToList();
Upvotes: 1
Views: 202
Reputation: 2360
You could use the PredicateBuilder class provided in the LinqKit package
In your package manager console:
Install-Package LinqKit
And then use the PredicateBuilder as follows:
var predicate = PredicateBuilder.True<Contact>();
foreach (var tagId in tagIds)
{
predicate = predicate.Or(c => c.Tags.Any(tag => tag.Id.ToString() == tagId));
}
var contactsByTags = context.Contacts.Include("Tags").Where(predicate).ToList();
Upvotes: 1