2009-12-02 81 views
2

說我有3 Dictionary<string, string>對象。所有3具有相同的密鑰像這樣:數據表中的字典

 
Dic1 Dic2 Dic3 
K V K V K V 
A s A z A i 
B d B e B u 
C a C r C o 
D w D t D p 

現在,我會想這些字典中的一個數據表合併,數據表應該是這樣的:

 
A s z i 
B d e u 
C a r o 
D w t p 

上如何任何指針或想法從單獨的字典中獲取DataTable中的組合字符?

+1

你的意思是 'A S Z I'? – Justin 2009-12-02 07:34:25

+0

呀,手指:) – Oxymoron 2009-12-02 07:36:07

回答

9
var dic1 = new Dictionary<string, string>() 
{ 
    { "A", "s" }, 
    { "B", "d" }, 
    { "C", "a" }, 
    { "D", "w" }, 
}; 

var dic2 = new Dictionary<string, string>() 
{ 
    { "A", "z" }, 
    { "B", "e" }, 
    { "C", "r" }, 
    { "D", "t" }, 
}; 

var dic3 = new Dictionary<string, string>() 
{ 
    { "A", "i" }, 
    { "B", "o" }, 
    { "C", "u" }, 
    { "D", "p" }, 
}; 

var table = new DataTable(); 
table.Columns.Add("K", typeof(string)); 
table.Columns.Add("c1", typeof(string)); 
table.Columns.Add("c2", typeof(string)); 
table.Columns.Add("c3", typeof(string)); 
foreach (var key in dic1.Keys) 
{ 
    table.Rows.Add(key, dic1[key], dic2[key], dic3[key]); 
} 
+0

Ofcourse,滑我怎麼會錯過這樣的:/ 我真的需要我的可視化技術工作更! 感謝:-) – Oxymoron 2009-12-02 07:51:39

0

假設DataTable被實例化並添加了列。

foreach (string k in Dic1.Keys) 
{ 
    DataRow row = table.NewRow(); 
    row[0] = k; 
    row[1] = Dic1[k]; 
    if (Dic2.ContainsKey(k)) 
     row[2] = Dic2[k]; 
    if (Dic3.ContainsKey(k)) 
     row[3] = Dic3[k]; 

    table.Rows.Add(row); 
}