【问题标题】:How to add a Dictionary<string,List<string>> to a DataTable in C#?如何在 C# 中将 Dictionary<string,List<string>> 添加到 DataTable?
【发布时间】:2015-11-27 06:51:10
【问题描述】:

我需要在 C# 中将 Dictionary&lt;string,List&lt;string&gt;&gt; 内容添加到数据表中。标题列名称应为字典中的Key,行应为List&lt;string&gt; 内容。 我怎样才能得到它?

代码:

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# 相同的字典/列表/数据表方法)
  • 但上面的链接包含字典列表。就我而言,我有包含列表的字典

标签: c# asp.net datatable


【解决方案1】:

这应该可行:

        Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();
        int rowcount = table.Rows.Count;
        int columnCount = table.Columns.Count;

        for (int c = 0; c <= columnCount; c++)
        {
            string columnName = table.Columns[c].ColumnName;
            List<string> tempList = new List<string>();

            for (int r = 0; r <= rowcount; r++)
            {
                var row = table.Rows[r];
                if (row[c] != DBNull.Value)
                    tempList.Add((string)row[c]);
                else
                    tempList.Add(null);
            }
            dict.Add(columnName, tempList);
        }

但正如其他人所提到的,将数据表转换为字典并不是一个好主意。在 cmets 中提到的具有不同长度的列通常不是真正的问题,因为您无法将值添加到列,您只能将行添加到您定义了列的表中。如果你没有给行中的某个列赋值,那么它将包含DBNull.Value,如果你没有将列设置为AllowDBNull = true,如果你不填写其中一个,你会得到一个错误列。所以永远不会有列比其他列多,因为这是不可能的。

【讨论】:

  • 这不再相关,因为问题显然变成了相反的......
猜你喜欢
  • 2018-08-04
  • 2012-09-21
  • 1970-01-01
  • 2019-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多