Enum to Dictionary in C#

前端 未结 10 2007
攒了一身酷
攒了一身酷 2020-12-02 15:10

I have searched this online, but I can\'t find the answer I am looking for.

Basically I have the following enum:

public enum typFoo : int
{
   itemA         


        
相关标签:
10条回答
  • 2020-12-02 15:40

    You can enumerate over the enum descriptors:

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

    That should put the value of each item and the name into your dictionary.

    0 讨论(0)
  • 2020-12-02 15:43

    Adapting Ani's answer so that it can be used as a generic method (thanks, 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());
    }
    
    0 讨论(0)
  • 2020-12-02 15:47

    Using reflection:

    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);
    }
    
    0 讨论(0)
  • 2020-12-02 15:48

    Another extension method that builds on Arithmomaniac's example:

        /// <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());
        }
    
    0 讨论(0)
  • 2020-12-02 15:51
    • Extension method
    • Conventional naming
    • One line
    • C# 7 return syntax (but you can use brackets in those old legacy versions of C#)
    • Throws an ArgumentException if the type is not System.Enum, thanks to Enum.GetValues
    • IntelliSense will be limited to structs (no enum constraint is available yet)
    • Allows you to use enum to index into the dictionary, if desired.
    public static Dictionary<T, string> ToDictionary<T>() where T : struct
      => Enum.GetValues(typeof(T)).Cast<T>().ToDictionary(e => e, e => e.ToString());
    
    0 讨论(0)
  • 2020-12-02 15:52

    See: How do I enumerate an enum in C#?

    foreach( typFoo foo in Enum.GetValues(typeof(typFoo)) )
    {
        mydic.Add((int)foo, foo.ToString());
    }
    
    0 讨论(0)
提交回复
热议问题