【发布时间】:2009-12-02 07:29:52
【问题描述】:
假设我有 3 个 Dictionary<string, string> 对象。所有 3 个都有相同的密钥,如下所示:
现在,我想将这些字典合并到一个 DataTable 中,DataTable 应如下所示:
阿斯齐 德优 卡罗尔 D w t p关于如何从单独的字典到 DataTable 中的组合字典的任何指针或想法?
【问题讨论】:
标签: c# dictionary datatable
假设我有 3 个 Dictionary<string, string> 对象。所有 3 个都有相同的密钥,如下所示:
现在,我想将这些字典合并到一个 DataTable 中,DataTable 应如下所示:
阿斯齐 德优 卡罗尔 D w t p关于如何从单独的字典到 DataTable 中的组合字典的任何指针或想法?
【问题讨论】:
标签: c# dictionary datatable
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]);
}
【讨论】:
假设 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);
}
【讨论】: