简体   繁体   English

C#循环遍历List <dictionary<string,string> &gt;填充DataTable

[英]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. 填充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. 列表中的每个字典都有一个Key,它需要是列名,而Value是该列中的值。 The list contains 225 dictionaries (225 rows to the table). 该列表包含225个词典(表格中有225行)。

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

See DataTable.NewRow . 请参见DataTable.NewRow

Reiview DataTable Class's example on how to work with a data table. Reiview DataTable Class关于如何使用数据表的示例。 But here is an example using Linq 但这是一个使用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): 结果(转储是LinqPad特定的不是.Net): 在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM