在foreach循环中从Enum获取值和名称

时间:2014-10-14 15:02:27

标签: c# dictionary enums

我有这个字典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);
    }
}

3 个答案:

答案 0 :(得分:4)

dic[Key] = row[key.ToString()].ToString();

编辑:我也看到了这个评论。如果这样做了回答,我将删除它:)

答案 1 :(得分:2)

我认为你可以在一个循环中完成它:

    // 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, row[Enum.GetName(typeof(Direction), key)].ToString());

修改 要获得枚举'value',只需将其转换为int:

    // 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, row[(int) key].ToString());

答案 2 :(得分:2)

尝试以下方法:

       foreach (TableKey key in Enum.GetValues(typeof(TableKey)))
       {
            dic[key] = row[key.ToString("G")].ToString();
       }