views:

24

answers:

1

Earlier I asked a question about merging a known number of dictionaries into 1 single DataTable: http://stackoverflow.com/questions/1831209/dictionaries-in-datatable Darin provided me with a satisfactory solution to the problem at hand. But my problemset has evolved. I can no long be certain of the amount of dictionaries I get supplied. In fact it can be any number between 1 and 10. Because of this the dictionaries are supplied to me in a collection, namely:

IList<IDictionary<string, string>> 
The solution for a static amount of dictionaries was given as follows:


    var dic1 = new Dictionary() 
{ 
    { "A", "s" },
    { "B", "d" },
    { "C", "a" },
    { "D", "w" },
};

var dic2 = new Dictionary() 
{ 
    { "A", "z" },
    { "B", "e" },
    { "C", "r" },
    { "D", "t" },
};

var dic3 = new Dictionary() 
{ 
    { "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]);
}

Now, how can I make this code work for a varying amount of dictionaries (especially the Rows.Add(xxx) part as each column in that row in essence is the value of a dictionary)

+1  A: 

I'm guessing:

foreach (var key in list[0].Keys) // assume the first defines everything
{
    object[] rowData = new object[list.Count + 1];
    rowData[0] = key;
    for(int i = 0 ; i < list.Count ; i++) {
        rowData[i+1] = list[i][key];
    }
    table.Rows.Add(rowData);
}

btw, it may (or maybe not) be easier to use params IDictionary<string, string>[] (in which case change .Count to .Length) - but either should work.

Marc Gravell
Thanks, I can certainly extrapolate this to my real world problemset!
Oxymoron