枚举到字典c#

时间:2011-04-07 15:36:25

标签: c# dictionary collections enums

我在线搜索但无法找到我要找的答案。 基本上我有以下枚举:

public enum typFoo : int
{
   itemA : 1,
   itemB : 2
   itemC : 3
}

如何将此枚举转换为Dictionary,以便将其存储在以下词典中

Dictionary<int,string> mydic = new Dictionary<int,string>();

和mydic看起来像这样:

1, itemA
2, itemB
3, itemC

有什么想法吗?

11 个答案:

答案 0 :(得分:140)

尝试:

var dict = Enum.GetValues(typeof(typFoo))
               .Cast<typFoo>()
               .ToDictionary(t => (int)t, t => t.ToString() );

答案 1 :(得分:42)

请参阅:How do I enumerate an enum?

foreach( typFoo foo in Enum.GetValues(typeof(typFoo)) )
{
    mydic.Add((int)foo, foo.ToString());
}

答案 2 :(得分:13)

调整Ani's answer以便将其用作通用方法(谢谢,toddmo):

public static Dictionary<int, string> EnumDictionary<T>()
{
    if (!typeof(T).IsEnum)
        throw new ArgumentException("Type must be an enum");
    return Enum.GetValues(typeof(T))
        .Cast<T>()
        .ToDictionary(t => (int)(object)t, t => t.ToString());
}

答案 3 :(得分:5)

public static class EnumHelper
{
    public static IDictionary<int, string> ConvertToDictionary<T>() where T : struct
    {
        var dictionary = new Dictionary<int, string>();

        var values = Enum.GetValues(typeof(T));

        foreach (var value in values)
        {                
            int key = (int) value;

            dictionary.Add(key, value.ToString());
        }

        return dictionary;
    }
}

用法:

public enum typFoo : int
{
   itemA = 1,
   itemB = 2,
   itemC = 3
}

var mydic = EnumHelper.ConvertToDictionary<typFoo>();

答案 4 :(得分:5)

  • 扩展方法
  • 常规命名
  • 一行
  • c#7返回语法(但您可以在c#的旧旧版本中使用括号)
  • 如果类型不是ArgumentException,则会引发System.Enum,感谢Enum.GetValues
  • Intellisense将仅限于结构(尚无enum约束)
  • 如果需要,允许您使用枚举索引到字典中。
public static Dictionary<T, string> ToDictionary<T>() where T : struct 
  => Enum.GetValues(typeof(T)).Cast<T>().ToDictionary(e => e, e => e.ToString());

答案 5 :(得分:3)

您可以枚举枚举描述符:

Dictionary<int, string> enumDictionary = new Dictionary<int, string>();

foreach(var name in Enum.GetNames(typeof(typFoo))
{
    enumDictionary.Add((int)((typFoo)Enum.Parse(typeof(typFoo)), name), name);
}

这应该将每个项目的值和名称放入字典中。

答案 6 :(得分:3)

+1到Ani。这是VB.NET版本

这是Ani的答案的VB.NET版本:

Public Enum typFoo
    itemA = 1
    itemB = 2
    itemC = 3
End Enum

Sub example()

    Dim dict As Dictionary(Of Integer, String) = System.Enum.GetValues(GetType(typFoo)) _
                                                 .Cast(Of typFoo)() _
                                                 .ToDictionary(Function(t) Integer.Parse(t), Function(t) t.ToString())
    For Each i As KeyValuePair(Of Integer, String) In dict
        MsgBox(String.Format("Key: {0}, Value: {1}", i.Key, i.Value))
    Next

End Sub

附加示例

就我而言,我想保存重要目录的路径并将它们存储在我的web.config的AppSettings部分。然后我创建了一个枚举来表示这些AppSettings的键...但我的前端工程师需要访问我们的外部JavaScript文件中的这些位置。因此,我创建了以下代码块并将其放在我们的主母版页中。现在,每个新的Enum项目将自动创建相应的javascript变量。这是我的代码块:

    <script type="text/javascript">
        var rootDirectory = '<%= ResolveUrl("~/")%>';
        // This next part will loop through the public enumeration of App_Directory and create a corresponding javascript variable that contains the directory URL from the web.config.
        <% Dim App_Directories As Dictionary(Of String, App_Directory) = System.Enum.GetValues(GetType(App_Directory)) _
                                                                   .Cast(Of App_Directory)() _
                                                                   .ToDictionary(Of String)(Function(dir) dir.ToString)%>
        <% For Each i As KeyValuePair(Of String, App_Directory) In App_Directories%>
            <% Response.Write(String.Format("var {0} = '{1}';", i.Key, ResolveUrl(ConfigurationManager.AppSettings(i.Value))))%>
        <% next i %>
    </script>

注意:在这个例子中,我使用枚举的名称作为键(而不是int值)。

答案 7 :(得分:3)

基于上述Arithmomaniacs示例的另一种扩展方法。

    /// <summary>
    /// Returns a Dictionary&lt;int, string&gt; of the parent enumeration. Note that the extension method must
    /// be called with one of the enumeration values, it does not matter which one is used.
    /// Sample call: var myDictionary = StringComparison.Ordinal.ToDictionary().
    /// </summary>
    /// <param name="enumValue">An enumeration value (e.g. StringComparison.Ordianal).</param>
    /// <returns>Dictionary with Key = enumeration numbers and Value = associated text.</returns>
    public static Dictionary<int, string> ToDictionary(this Enum enumValue)
    {
        var enumType = enumValue.GetType();
        return Enum.GetValues(enumType)
            .Cast<Enum>()
            .ToDictionary(t => (int)(object)t, t => t.ToString());
    }

答案 8 :(得分:1)

使用反射:

Dictionary<int,string> mydic = new Dictionary<int,string>();

foreach (FieldInfo fi in typeof(typFoo).GetFields(BindingFlags.Public | BindingFlags.Static))
{
    mydic.Add(fi.GetRawConstantValue(), fi.Name);
}

答案 9 :(得分:0)

如果您只需要名称,则根本不需要创建该词典。

这会将枚举转换为int:

 int pos = (int)typFoo.itemA;

这会将int转换为enum:

  typFoo foo = (typFoo) 1;

这会让你知道它的名字:

 ((typFoo) i).toString();

答案 10 :(得分:0)

public class EnumUtility
    {
        public static string GetDisplayText<T>(T enumMember)
            where T : struct, IConvertible
        {
            if (!typeof(T).IsEnum)
                throw new Exception("Requires enum only");

            var a = enumMember
                    .GetType()
                    .GetField(enumMember.ToString())
                    .GetCustomAttribute<DisplayTextAttribute>();
            return a == null ? enumMember.ToString() : a.Text;
        }

        public static Dictionary<int, string> ParseToDictionary<T>()
            where T : struct, IConvertible
        {
            if (!typeof(T).IsEnum)
                throw new Exception("Requires enum only");

            Dictionary<int, string> dict = new Dictionary<int, string>();
            T _enum = default(T);
            foreach(var f in _enum.GetType().GetFields())
            {
               if(f.GetCustomAttribute<DisplayTextAttribute>() is DisplayTextAttribute i)
                    dict.Add((int)f.GetValue(_enum), i == null ? f.ToString() : i.Text);
            }
            return dict;
        }

        public static List<(int Value, string DisplayText)> ParseToTupleList<T>()
            where T : struct, IConvertible
        {
            if (!typeof(T).IsEnum)
                throw new Exception("Requires enum only");

            List<(int, string)> tupleList = new List<(int, string)>();
            T _enum = default(T);
            foreach (var f in _enum.GetType().GetFields())
            {
                if (f.GetCustomAttribute<DisplayTextAttribute>() is DisplayTextAttribute i)
                    tupleList.Add(((int)f.GetValue(_enum), i == null ? f.ToString() : i.Text));
            }
            return tupleList;
        }
    }