Say I have 3 Dictionary<string, string>
objects. All 3 have the same key like so:
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
Now, I would want to combine these dictionaries in to one DataTable, the DataTable should look like:
A s z i B d e u C a r o D w t p
Any pointers or ideas on to how to get from t开发者_如何学Gohe seperate dictionaries to the combined ones in the 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]);
}
Assuming DataTable is instantiated and columns added.
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);
}
精彩评论