2012-05-21 35 views
8

我有關於LINQ的/λ問題和了以下問題:C#字典相交

我有兩個字典,伯和仲...這些兩個字典被定義爲關鍵=字符串,值= INT。如果KEYS與二級字典相交,我需要修剪主字典。

即:

primaryDict = ["thing1", 33] ["thing2", 24] ["thing3", 21] ["thing4", 17] ["thing5", 12] 

secondaryDict = ["thing1", 22] ["thing3", 20] ["thing4", 19] ["thing7", 17] ["thing9", 10] 

resultDict = ["thing1", 33] ["thing3", 21] ["thing4", 17] 

我嘗試:

resultDict = primaryDict.Keys.Intersect(secondaryDict.Keys).ToDictionary(t => t.Key, t.Value); 

這顯然是因爲primaryDict.Keys.Intersect是返回鍵列表不工作...我將如何重新建立一個新的字典,或對主詞典?任何幫助,將不勝感激。

回答

17

你可以這樣做:

resultDict = primaryDict.Keys.Intersect(secondaryDict.Keys) 
           .ToDictionary(t => t, t => primaryDict[t]); 

,或者可選地:

resultDict = primaryDict.Where(x => secondaryDict.ContainsKey(x.Key)) 
         .ToDictionary(x => x.Key, x => x.Value); 

後者可能是稍微更有效,因爲避免了扔掉的集合的創建(一個由相交方法產生),而且不需要的第二接入逐鍵到primaryDict

編輯(按評論):

resultDict = 
primaryDict.Where(x => secondaryDict.ContainsKey(x.Key)) 
      .ToDictionary(x => x.Key, x => x.Value + secondaryDict[x.Key]); 
+1

我認爲最後一個版本是好多了,因爲我不認爲治療字典作爲一個IEnumerable將利用字典,併爲O運行(n)時間。 –

+0

這對我正在做的事情非常有用......我使用了第二種解決方案,並且所有事情都按預期工作。你搖滾戴夫! –

+0

作爲後續...是否有可能在這個相同的表達式中求和值? –

2

未經測試:

resultDict = primaryDict.Keys.Intersect(secondaryDict.Keys).ToDictionary(t => t.Key, primaryDict[t.Key]); 
3

你仍然可以使用primaryDict你的LINQ的語句中,因爲你正在創建一個詞典,這只是它一旦建立被分配給您的變量:

resultDict = primaryDict.Keys 
         .Intersect(secondaryDict.Keys) 
         .ToDictionary(t => t, primaryDict[t]);