2015-04-03 40 views
0

我有我想要檢索的結果匹配到這些列表的字典如何從詞典<字符串,對象>

這裏是我迄今所做

  Dictionary<string, Dictionary<string, int>> SomeDictionary = new Dictionary<string, Dictionary<string, int>>(); 
     List<int> MyList = new List<int>() 
     { 

      2,3,4,5 
     }; 

     Dictionary<string, int> internalDictionary = new Dictionary<string, int>(); 
     internalDictionary.Add("two", 2); 
     internalDictionary.Add("three", 3); 
     internalDictionary.Add("four", 4); 
     internalDictionary.Add("five", 5); 

     Dictionary<string, int> AnotherDictionary = new Dictionary<string, int>(); 
     AnotherDictionary.Add("six", 6); 
     AnotherDictionary.Add("three", 3); 
     AnotherDictionary.Add("seven", 7); 


     SomeDictionary.Add("Dictionary1", internalDictionary); 
     SomeDictionary.Add("Dictionary2", AnotherDictionary); 


     var res = from l in MyList 
        select(from q in 
        (from p in 
         (from s in SomeDictionary 
         select s) 
        select p) where q.Value.Equals(l) select q); 

的獲得價值返回的值爲null。我在想什麼?

我需要匹配KeyValuePair其中值匹配內部字典值。

+2

你好,你正在比較'對象'(2,3,4,...)和'strings'('「2」',...),除了'from c in col select c == col' – Carsten 2015-04-03 06:55:09

+0

是的,我應該怎麼做? – Rohit 2015-04-03 06:59:07

回答

1

試試這個:

var res = from l in MyList 
       from q in SomeDictionary 
       from w in q.Value 
       where w.Value == l 
       select w; 

我得到這個:

res

+1

跟我說說吧!當球門柱繼續移動時很難踢進球門...... – Enigmativity 2015-04-03 07:03:08

3

說明:

  1. 很多選擇所有的內部字典合併到所有在一個字典。
  2. List和SelectMany是IEnumerable。因此可以在IEnumerable對象之間進行連接。
  3. 但是,List包含字符串值,而從SelectMany返回的IEnumerable對象具有整數值。

因此,在將整數轉換爲字符串後,創建了帶字符串和整數值的內部聯接查詢。請參閱截屏可能需要輸出

Screen cast showing working code

這Linq的片斷可能會有所幫助:

var allinone = (from l in MyList 
         join d in SomeDictionary.SelectMany(s => s.Value) on l equals d.Value 
         select d); 
+1

什麼改變了?請詳細說明你的答案。 – 2015-04-03 06:56:40

+0

你甚至可以用編譯器檢查過嗎?爲什麼這應該有幫助?問題的關聯在哪裏? – Carsten 2015-04-03 06:56:50

+0

請參考完整答案。 – vrluckyin 2015-04-03 06:57:47

相關問題