【发布时间】:2014-10-14 15:02:27
【问题描述】:
我有这本字典 Dictionary<TableKey, string>,其中 TableKey 是枚举类型。
我正在尝试使用我在 sql 查询期间获取的 DataSet 对象中的数据填充字典
DataSet resultSet = Utils.RunQuery(sqlQuery);
if (resultSet.Tables.Count > 0)
{
foreach (DataRow row in resultSet.Tables[0].Rows)
{
// Makes the dictionary with populated keys from enum
Dictionary<TableKey, string> dic = new Dictionary<TableKey, string>();
foreach (TableKey key in Enum.GetValues(typeof(TableKey)))
dic.Add(key, "");
// the foreach loop in question, which should insert row data into the dic
foreach (TableKey key in Enum.GetValues(typeof(TableKey)))
dic[key] = row[key.GetName()].ToString(); // This line does not work!
// adds dictionary to my list of dictionaries
latestEntryList.Add(dic);
}
}
我正在尝试使用上述代码中的 forloop 来替换它。
dic[TableKey.Barcode] = row["Barcode"].ToString();
dic[TableKey.FullName] = row["FullName"].ToString();
dic[TableKey.Location] = row["Location"].ToString();
dic[TableKey.Notes] = row["Notes"].ToString();
dic[TableKey.Category] = row["Category"].ToString();
dic[TableKey.Timestamp] = row["Timestamp"].ToString();
dic[TableKey.Description] = row["Description"].ToString();
编辑:也许有一种方法可以将两个 foreach 循环合并为一个。
编辑:我需要获取枚举的字符串名称和键值本身。
public enum TableKey
{
Barcode = 0,
FullName = 1,
Location = 2,
Notes = 3,
Category = 4,
Timestamp = 5,
Description = 6
}
解决方案
DataSet resultSet = Utils.RunQuery(sqlQuery);
if (resultSet.Tables.Count > 0)
{
foreach (DataRow row in resultSet.Tables[0].Rows)
{
Dictionary<TableKey, string> dic = new Dictionary<TableKey, string>();
foreach (TableKey key in Enum.GetValues(typeof(TableKey)))
dic.Add(key, row[key.ToString()].ToString());
latestEntryList.Add(dic);
}
}
【问题讨论】:
-
您遇到了什么问题?
-
我无法让 forloop 正常工作。我认为我使用了错误的方法。
-
不应该只是:
dic[key] = row[key.ToString()].ToString() -
当您说无法正常工作时,您的意思是什么?例外?还是错误的数据?
-
不,我的意思是我需要正确设置它。我无法正确组合方法。
标签: c# dictionary enums