2013-02-08 49 views
1

在我的代碼有行字典聯盟到字典?

var d3 = d.Union(d2).ToDictionary(s => s.Key, s => s.Value); 

這種感覺奇怪,因爲它很可能我會做這個有很多。沒有.ToDictionary()。如何合併字典並將其保存爲字典?

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      var list = new List<Tuple<int, string>>(); 
      list.Add(new Tuple<int, string>(1, "a")); 
      list.Add(new Tuple<int, string>(3, "b")); 
      list.Add(new Tuple<int, string>(9, "c")); 
      var d = list.ToDictionary(
       s => s.Item1, 
       s => s.Item2); 
      list.RemoveAt(2); 
      var d2 = list.ToDictionary(
       s => s.Item1, 
       s => s.Item2); 
      d2[5] = "z"; 
      var d3 = d.Union(d2).ToDictionary(s => s.Key, s => s.Value); 
     } 
    } 
} 
+0

這可能有助於:http://stackoverflow.com/questions/294138/merging-dictionaries-in-c-sharp – sgeddes 2013-02-08 14:16:17

回答

10

使用的「直線」 Union的是,它不解釋的字典辭書的問題;它將字典解釋爲IEnumerable<KeyValyePair<K,V>>。這就是爲什麼你需要最後的ToDictionary步驟。

如果你的詞典中沒有重複鍵,這應該更快一點:

var d3 = d.Concat(d2).ToDictionary(s => s.Key, s => s.Value); 

注意,Union方法將打破太多,如果兩個庫包含具有不同的值相同的密鑰。如果字典包含相同的密鑰(即使它對應於相同的值),則將破壞Concat

+0

他們有相同的鍵,但他們有相同的值。另外我試圖擺脫ToDictionary步驟。但Concat看起來不錯 – BruteCode 2013-02-08 14:51:19