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

本文关键字:获取 Enum foreach 循环 | 更新日期: 2023-09-27 18:26:25

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

编辑:也许有一种方法可以将两个前臂循环合并为一个。

EDIT:我需要获取枚举的字符串名称和键值本身。

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

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

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

编辑:我也看到了这样的评论。如果答案是这样的,我会删除这个:)

尝试以下操作:

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

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

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