Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# looping through List<dictionary<string,string>> to populate a DataTable

I need to loop through a List of Dictionaries

List<Dictionary<string,string>> 

to populate a DataTable. Each Dictionary in the list has a Key, which needs to be the column name, and a Value which is what's in that column. The list contains 225 dictionaries (225 rows to the table).

List<Dictionary<string, string>> myList = 
       JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(jsonRep);
DataTable dt = new DataTable();

    //loop through list, loop through dictionaries, add keys as columns, 
    //values as rows.                     

so far, I have been trying..

//get max columns
int columns = myList[0].Count; <--gives me 13
//add columns
for (int i = 0; i < columns; i++)
   dt.Columns.Add(string myList[i].Keys);  <--somehow get to the key in dict to add as column names         
//add rows
foreach (var x in myList)
{
     dt.Rows.Add(x); <--not working
}
jsonReprValue = dt; <--save new DataTable to var jsonReprValue

How do I do this correctly? Thanks!

like image 659
Tonia Roddick Avatar asked Feb 20 '23 04:02

Tonia Roddick


1 Answers

You have two problems. One is adding the columns, and the other is adding the rows.

Adding the columns

Assuming your list has items in it, and that all the dictionaries in the list have the same keys, then you only need to add columns from one of the dictionaries:

foreach(string column in myList[0].Keys)
{
    dt.Columns.Add(column);
}

Adding the Rows

Change this:

foreach (var x in myList)
{
    dt.Rows.Add(x); <--not working
}

To this:

foreach(Dictionary<string, string> dictionary in myList)
{
    DataRow dataRow = dt.NewRow();

    foreach(string column in dictionary.Keys)
    {
        dataRow[column] = dictionary[column];
    }

    dt.Rows.Add(dataRow);
}

See DataTable.NewRow.

like image 84
Seth Flowers Avatar answered May 03 '23 04:05

Seth Flowers