Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A Linq ContainsAll Method?

Tags:

c#

linq

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
like image 348
Steven Wood Avatar asked Sep 26 '14 12:09

Steven Wood


2 Answers

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));
like image 160
Selman Genç Avatar answered Nov 09 '22 05:11

Selman Genç


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;

        }
like image 41
kishore V M Avatar answered Nov 09 '22 06:11

kishore V M