I have a list of items that can each have multiple keywords so I have three tables
Item -> ItemKeyword <- Keyword
I want to return all Items where the Item has all keywords in a list. so for example:
Item 1 has keywords "Rabbit", "Dog", "Cat"
Item 2 has keywords "Rabbit", Hedgehog", "Dog"
I want to return only those items that have both "Dog" and "Cat" as keywords.
I cant use a contains query as that will essentially return all those items with "Dog" OR "Cat".
So I guess what I am asking for is if there is such a thing called ContainsAll in linq, or if there is some way I can perform this functionality.
I have attempted to use Except and Intersect but I cant seem to get the correct results.
I would like to have a single query so that it is easy to compile the query but this is not a dealbreaker.
I am using:
I cant use a contains query as that will essentially return all those items with "Dog" OR "Cat".
This is simply not true. You can use two contains with an AND
&& :
items.Where(item => item.Keywords.Contains("Dog") && item.Keywords.Contains("Cat"));
Or you can put the values you are looking for in an array then use All
method to make it shorter:
var values = new [] { "Dog", "Cat" };
items.Where(item => values.All(item.Keywords.Contains));
Please check this .. code is written lengthier for better understanding .. Assuming each item as an identifier to check
List<item> ItemsList = new List<item>();
item item1 = new item();
item1.ID = "1";
item1.keywords = new List<string>();
item1.keywords.Add("Rabbit");
item1.keywords.Add("Dog");
item1.keywords.Add("Cat");
ItemsList.Add(item1);
item item2 = new item();
item2.ID = "2";
item2.keywords = new List<string>();
item2.keywords.Add("Rabbit");
item2.keywords.Add("Hedgehog");
item2.keywords.Add("Dog");
ItemsList.Add(item2);
//this the list you want to check
var values = new List<string> ();
values.Add("Dog");
values.Add("Cat");
var result = from x in ItemsList
where !(values.Except(x.keywords).Any())
select x;
foreach (var item in result)
{
// Check the item.ID;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With