如何从数据表中将数据附加到字典?

时间:2016-12-23 03:49:07

标签: c# dictionary datatable

我有一个包含两列的数据表。如何将我的数据表行添加到我的字典中?

Dictionary<string, object> lst = new Dictionary<string, object>();
 try
   {
DataTable dt = new DataTable();
  foreach (DataRow row in dt.Rows)
     {
      lst.Add(row["Inuse"].ToString(), row["Inuse"] as string);
        lst.Add(row["Time"].ToString(), row["Time"] as string);
     }

    }
     catch (Exception ex)
       {
        throw ex;
        }
return lst;

但我无法将我的行添加到dictionary.suggest中。

2 个答案:

答案 0 :(得分:0)

这可能会为你做到这一点

dt.AsEnumerable().Select(
                    row => dt.Columns.Cast<DataColumn>()
                .ToDictionary(
                        column => column.ColumnName as string, 
                        column => row["Time"] as object
                             )
                        );

答案 1 :(得分:0)

Dictionary<string, object> lst = new Dictionary<string, object>();
try
{
    foreach (DataRow row in dt.Rows)
    {
        //Adds time as key and Inuse as value in dictionary
        lst.Add(row["Time"].ToString(), row["Inuse"] as string);
    }
}
catch (Exception ex)
{
    throw ex;
}