假设我有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
现在,我想将这些词典合并到一个DataTable中,DataTable应该如下所示:
A s z i B d e u C a r o D w t p
关于如何从单独的词典到DataTable中的组合词典的任何指示或想法?
答案 0 :(得分: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]);
}
答案 1 :(得分: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);
}