C# 循环遍历 List<dictionary<string,string>>填充数据表 [英] C# looping through List&lt;dictionary&lt;string,string&gt;&gt; to populate a DataTable

查看:21
本文介绍了C# 循环遍历 List<dictionary<string,string>>填充数据表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要遍历字典列表

List<Dictionary<string,string>> 

填充数据表.列表中的每个字典都有一个键,它需要是列名,以及一个值,它是该列中的内容.该列表包含 225 个字典(表的 225 行).

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.

添加列

假设您的列表中有项目,并且列表中的所有词典都具有相同的键,那么您只需要添加其中一个词典中的列:

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

添加行

改变这个:

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

为此:

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

请参阅 DataTable.NewRow.

这篇关于C# 循环遍历 List<dictionary<string,string>>填充数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆