anya anya - 2 months ago 41
C# Question

Convert Dictionary<string, Dictionary<string, string>> to a data table

I have a Dictionary> where the first group of keys should be the column name and the Second group of keys should be the row names and the values are the values of the inner dictionary.
How do I convert this to a data table in C#?
Thanks in advance.
EDIT: The row names are unique and are present as the key in the dictionary. The dictionary is sort of like a matrix.


Here's my crack at it.

    static DataTable DictionaryToDataTable(Dictionary<string,Dictionary<string,string>> dictionary)
        int index;
        string key = "YourPrimaryKeyColumnNameHere";
        DataTable dt = new DataTable();

        // Setting primary key allows you to perform Find() and IndexOf() later on
        dt.PrimaryKey = new DataColumn[] { dt.Columns[key] };

        foreach (var header in dictionary)
            foreach (var row in header.Value)
                index = dt.Rows.IndexOf(dt.Rows.Find(row.Key));

                // Index will be -1 if the row isn't found, ie on the first iteration
                if (index < 0)
                    // When creating a new row, start it with the unique primary key field
                    dt.Rows.Add(new[] { row.Key });
                    // We use dt.Rows.Count - 1 to get the last (newly added) row
                    dt.Rows[dt.Rows.Count - 1][header.Key] = row.Value;
                    dt.Rows[index][header.Key] = row.Value;
        return dt;