Dictionaries in DataTable

2020-06-27 09:01发布

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 the seperate dictionaries to the combined ones in the DataTable?

2条回答
狗以群分
2楼-- · 2020-06-27 09:25

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);
}
查看更多
你好瞎i
3楼-- · 2020-06-27 09:30
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]);
}
查看更多
登录 后发表回答