【发布时间】:2015-11-27 06:51:10
【问题描述】:
我需要在 C# 中将 Dictionary<string,List<string>> 内容添加到数据表中。标题列名称应为字典中的Key,行应为List<string> 内容。
我怎样才能得到它?
代码:
DataTable new_dt = new DataTable();
//Header Columns
foreach (string item in splits)
{
DataColumn col = new DataColumn(item, typeof(System.String));
new_dt.Columns.Add(col);
}
foreach (DataColumn col in new_dt.Columns)
{
//Declare the bound field and allocate memory for the bound field.
BoundField bfield = new BoundField();
//Initalize the DataField value.
bfield.DataField = col.ColumnName;
//Initialize the HeaderText field value.
bfield.HeaderText = col.ColumnName;
//Add the newly created bound field to the GridView.
gvMatrix.Columns.Add(bfield);
}
//Content Loading
foreach (KeyValuePair<string, List<string>> item in _dict)
{
string[] ss = item.Value.ToArray();
foreach (string s in ss)
{
DataRow row = new_dt.NewRow();
row[item.Key] = s;
new_dt.Rows.Add(row);
}
}
gvMatrix.DataSource = new_dt;
gvMatrix.DataBind();
【问题讨论】:
-
到目前为止你尝试过什么?
-
如果其中一个列表不如其他列表长怎么办?正如您所说的那样,您想将键用作列名,将内容用作其下的行。因此,当其中一列的行数不同时会出现什么问题? (根据您通常如何构建字典,我会在那里执行 1 个数据表 PER 字典条目,因为其他所有内容都是.....潘多拉魔盒,如果您不能确保每个键下的条目数量相同)跨度>
-
附加说明:因为您已将 asp.net 添加为标签。你确定吗?即使它是一个 asp.net 程序,您所拥有的代码都不是 asp.net 特定的,所以我认为没有必要使用该标记(因为 asp.net 具有与 c# 相同的字典/列表/数据表方法)
-
但上面的链接包含字典列表。就我而言,我有包含列表的字典