简体   繁体   English

如何添加字典 <string,List<string> &gt;到C#中的数据表?

[英]How to add a Dictionary<string,List<string>> to a DataTable in C#?

I need to add Dictionary<string,List<string>> contents to a Data Table in C#. 我需要将Dictionary<string,List<string>>内容添加到C#中的数据表中。 The Header column name should be the Key in Dictionary and the rows should be the List<string> contents. 标题列名称应为“字典中的Key ,行应为List<string>内容。 How can I get it? 我怎么才能得到它?

Code: 码:

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

This should work: 这应该工作:

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

But as others have mentioned, it isn't a really good idea to convert a datatable into a dictionary.The columns having different lenghts as mentioned in the comments aren't really a problem normally as you can't add values to columns, you can only add rows to a table of which you defined the columns. 但是正如其他人提到的那样,将数据表转换为字典并不是一个好主意。注释中提到的具有不同长度的列通常并不是真正的问题,因为您无法向列添加值,只能将行添加到定义了列的表中。 If you don't give a value to a certain column in the row, then it will contain DBNull.Value , if you haven't set the column to AllowDBNull = true you will get an error if you don't fill in one of the columns. 如果您未为该行中的特定列提供值,则该列将包含DBNull.Value ;如果您尚未将该列设置为AllowDBNull = true ,则如果您不填写以下内容之一,则会收到错误消息列。 So there will never be columns with more rows than the other ones because that's impossible. 因此,行数永远不会比其他列多,因为那是不可能的。

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

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