简体   繁体   中英

How to convert Dictionary<string, List<object>> into DataTable in C#?

I have a Dictionary<string, AFValues> which AFValues is a collection of type AFValue object.

A snapshot of what is behind the scene of the dictionary data structure: 在此处输入图片说明

The Value for each Key has this AFValues collection: 在此处输入图片说明

Then, this is what I have written so far to convert the dictionary into a data table.

private DataTable dataTable = null;    
private DataTable ConvertToDataTable(Dictionary<string, AFValues> dict)
        {
            using (dataTable = new DataTable())
            {
                if (dict.Count > 0)
                {
                    var headers = dict.Keys;
                    foreach (var colHeader in headers)
                    {
                        dataTable.Columns.Add(colHeader);
                    }

                    foreach (var row in dict)
                    {
                        DataRow dataRow = dataTable.NewRow();
                        foreach (var afVal in row.Value)
                        {
                            dataRow[row.Key] = afVal.Value;
                        }
                        dataTable.Rows.Add(dataRow);
                    }
                }
            }
            return dataTable;
        }

I have successfully created the DataTable columns based on the dict.Keys which is fairly straightforward. However, my problem lies on how to correctly loop through AFValues and mapped each AFValue to their corresponding column ( dict.Key )?

I have done my research, but couldn't find any related scenario which is the same as mine.

This is the returned DataTable based on the code above which is incorrect.

在此处输入图片说明

This should be the expected output (sample table)

在此处输入图片说明

Any help is greatly appreciated.

You can use a code block like this for your inner loop:

for (int i = 0; i < dict.Values.Max(item => item.Count()); i++)
{
    DataRow dataRow = dataTable.NewRow();

    foreach (var key in dict.Keys)
    {
        if (dict[key].Count > i)
            dataRow[key] = dict[key][i];
    }
    dataTable.Rows.Add(dataRow);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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