Search code examples
c#linq

A Linq ContainsAll Method?


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:

  1. Dot Net 4.5
  2. Visual Studio 2012
  3. C#
  4. Linq
  5. Entity Framework
  6. Sql Server Ce 4.0

Solution

  • 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;
        
    }