2010-08-02 157 views
2

我有兩個字典一樣比較和合並字典

Dictionary<String,List<String>> DictOne=new Dictionary<String,List<String>>() 
    Dictionary<String,List<String>> DictTwo=new Dictionary<String,List<String>>() 

DictOne 


KeyOne  "A" 
      "B" 

KeyTwo  "C" 
      "D" 

KeyThree "X" 
      "Y" 



DictTwo 

Key1  "X" 
      "Z" 
      "Y" 

Key2  "A" 


Key3  "C" 
     "D" 

Key4  "M" 
     "N" 

我需要比較且不論兩個dictonaries合併的關鍵和將數據添加到第三字典

Dictionary<String,List<String>> DictThree=new Dictionary<String,List<String>>() 

所以第三個字典將包含

DictThree 

KeyOne "A" 
     "B" 

KeyTwo "C" 
     "D" 

KeyThree "X" 
     "Y" 
     "Z" 

Key4  "M" 
     "N" 

現在,我通過兩個dictionar迭代IES

現在,我使用像

首先我要在DictOne第一個列表,然後在搜索列表中的項目是否存在於DictTwo任何列表中,如果這樣進行合併操作,然後添加使用任何一個鍵(鍵入DictOne或DictTwo)將結果列表放入第三個詞典中。如果列表不存在,則將該列表與鍵一起添加到第三個詞典中。同樣將在DictOne而DictTwo

所有列表執行有沒有辦法做到這一點使用LINQ提前

感謝

回答

2

Whe!相當大的挑戰。基本上,他們是字典這一事實是完全不相關的,你只需要每個字典的Dictionary<,>.Values部分,所以我只是要使用一個字符串數組(string[][])的數組作爲這個例子。

var group1 = new string[][] { new[] { "A", "B" }, new[] { "C", "D" }, new[] { "X", "Y" } }; 
var group2 = new string[][] { new[] { "X", "Y", "Z" }, new[] { "A" }, new[] { "C", "D" }, new[] { "M", "N" } }; 

// For each array in group1, check if it has matching array in group2, if 
// it does, merge, otherwise just take the array as is. 
var group1Join = from g1 in group1 
       let match = group2.SingleOrDefault(g2 => g1.Intersect(g2).Any()) 
       select match != null ? g1.Union(match) : g1; 

// Take all the group2 arrays that don't have a matching array in group1 and 
// thus were ignored in the first query. 
var group2Leftovers = from IEnumerable<string> g2 in group2 
         where !group1.Any(g1 => g2.Intersect(g1).Any()) 
         select g2; 

var all = group1Join.Concat(group2Leftovers); 

編輯:更正代碼工作在C#3.0,而不是依賴於C#4.0的協方差支持。

+0

我不知道爲什麼這個答案被否決,因爲它實際上似乎正確回答了這個有點不明確的問題。 – 2010-08-02 11:47:11

+0

更有趣的是,這個問題在四個不同的答案上有不少於4個的降低評分,沒有任何一個解釋原因的評論。 – 2010-08-02 11:52:01

+0

@ Allon Guralnek:所有的答案都只是簡單的說明你的兩本詞典。 而在你的回答中,IEnumerable 無法轉換爲 IEnumerable > – 2010-08-02 12:01:15

-1

你可以這樣做:

Dictionary<String, List<String>> DictThree = DictOne.Concat(DictTwo); 

或者這,如果您需要將其保留爲字典:

Dictionary<String, List<String>> DictThree = DictOne.Concat(DictTwo).ToDictionary(x => x.Key); 
-1

您可以使用此認可CH:

var dict3 = DictOne 
    .Concat(DictTwo) 
    .GroupBy(x => x.Key) 
    .ToDictionary(x => x.Key, x => x.SelectMany(y => y.Value).ToList()); 

當然,如果你想使用自己的平等的比較,就可以起到的IEqualityComparer到的GroupBy方法,第二個參數。

-1

如果你想要的是,你合併的每個列表中鍵的所有條目,你可以做到這一點,像這樣:

var dictThree = (from kv in dictOne.Concat(dictTwo) 
        group kv.Value by kv.Key) 
    .ToDictionary(k => k.Key, v => v.SelectMany(l => l).Distinct().ToList()); 

這將在每個鍵每個列表產生不同的字符串。

+0

這只是concatinating這兩個字典。我需要基於價值而不是密鑰 – 2010-08-02 12:04:37

+0

進行協調那麼,這個問題有點含糊不清,不是嗎? ;-) – 2010-08-02 12:16:38