问题描述:

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!

网友答案:

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(row);
}

See DataTable.NewRow.

网友答案:

Reiview DataTable Class's example on how to work with a data table. But here is an example using Linq

List<Dictionary<string, string>> myList = new List<Dictionary<string, string>>()
                                                       { new Dictionary<string,string>() { { "ABC", "This" },
                                                                                           { "DEF", "is" },
                                                                                           { "GHI", "radio" },
                                                                                           { "JKL", "clash" } } };

DataTable dt = new DataTable();

// Add columns first
dt.Columns.AddRange( myList.First ()
                           .Select (kvp => new DataColumn() { ColumnName = kvp.Key, DataType = System.Type.GetType("System.String")} )
                           .AsEnumerable()
                           .ToArray()
                           );

// Now add the rows
myList.SelectMany (Dict => Dict.Select (kvp => new {
                                                    Row = dt.NewRow(),
                                                    Kvp = kvp
                                                    }))
      .ToList()
      .ForEach( rowItem => {
                              rowItem.Row[rowItem.Kvp.Key] = rowItem.Kvp.Value;
                              dt.Rows.Add( rowItem.Row );
                           }
             );
dt.Dump();

The result (Dump is LinqPad specific not .Net):

相关阅读:
Top