2014-09-26 35 views
0

我有項目,可以各有多個關鍵字的列表,以便我有三個表一個Linq ContainsAll方法?

Item -> ItemKeyword <- Keyword 

我想回到這裏該項目已在列表中的所有關鍵字的所有項目。例如:

Item 1 has keywords "Rabbit", "Dog", "Cat" 
Item 2 has keywords "Rabbit", Hedgehog", "Dog" 

我只想返回那些同時包含「Dog」和「Cat」作爲關鍵字的項目。

我不能使用一個包含查詢,因爲這將基本上返回所有這些項目與「狗」或「貓」。

所以我想我要求的是,如果有這樣的事情叫做ContainsAll in linq,或者如果有一些方法我可以執行此功能。

我試圖使用Except和Intersect,但我似乎無法得到正確的結果。

我想有一個單一的查詢,這樣很容易編譯查詢,但這不是一個dealbreaker。

我使用:

  1. 點NET 4.5
  2. 的Visual Studio 2012
  3. C#
  4. 的LINQ
  5. 實體框架
  6. 的SQL Server CE 4.0
+3

除w唉,我會說 - 讓我們看看你有什麼。我期望'!largeCollection.Except(smallCollection).Any())'檢查'smallCollection'中的所有內容都在'largeCollection'中。 – 2014-09-26 12:10:45

+1

我會使用'Intersect' - 'if(largeCollection.Intersect(smallCollection).Count == smallCollection.Count)'應該聲明所有來自'smallCollection'的項目也都在'largeCollection'中。 – Pafka 2014-09-26 12:13:23

+0

或者'largeCollection.Where(x => x.Keywords.Contains(「Dog」)&& x.Keywords.Contains(「Cat」))'這樣可以避免創建另一個集合,並且可讀性更強,但Jon更簡潔。 – helrich 2014-09-26 12:14:01

回答

1

請檢查此..代碼被寫的更長,以便更好地理解。假定每個項目作爲要檢查的標識符

 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; 

     } 
+0

這非常感謝很多! – 2014-09-26 13:20:25

1

我無法使用包含查詢,因爲這將基本上返回所有這些項目與「狗」或「貓」。

這根本不是真的。您可以使用兩種含有與AND & &:

items.Where(item => item.Keywords.Contains("Dog") && item.Keywords.Contains("Cat")); 

或者你可以把你正在尋找一個數組,然後使用All方法的值,使之更短:

var values = new [] { "Dog", "Cat" }; 
items.Where(item => values.All(item.Keywords.Contains));