[英]How to convert Dictionary<string, List<object>> into DataTable in C#?
[英]How to add a Dictionary<string,List<string>> to a DataTable in C#?
我需要將Dictionary<string,List<string>>
內容添加到C#中的數據表中。 標題列名稱應為“字典中的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();
這應該工作:
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);
}
但是正如其他人提到的那樣,將數據表轉換為字典並不是一個好主意。注釋中提到的具有不同長度的列通常並不是真正的問題,因為您無法向列添加值,只能將行添加到定義了列的表中。 如果您未為該行中的特定列提供值,則該列將包含DBNull.Value
;如果您尚未將該列設置為AllowDBNull = true
,則如果您不填寫以下內容之一,則會收到錯誤消息列。 因此,行數永遠不會比其他列多,因為那是不可能的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.