views:

278

answers:

3

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?

A: 

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);
}
o.k.w
+6  A: 
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]);
}
Darin Dimitrov
Ofcourse, how did I miss this :/I really need to work on my visualization skills more!Thanks :-)
Oxymoron
A: 

Though Darins' solution is satisfactory when the amount of dictionaries is known on beforehand. The situation has risen where the amount of dictionaries can vary (anything between 1 and 10). The dictionaries are thus packed in a collection, as follows:

IList<IDictionary<string, string>>

I started by using a foreach construction to iterate through the List, but then?

Oxymoron