Enum to Dictionary in C#

前端 未结 10 2030
攒了一身酷
攒了一身酷 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:48

    Another extension method that builds on Arithmomaniac's example:

        /// 
        /// Returns a Dictionary<int, string> 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().
        /// 
        /// An enumeration value (e.g. StringComparison.Ordianal).
        /// Dictionary with Key = enumeration numbers and Value = associated text.
        public static Dictionary ToDictionary(this Enum enumValue)
        {
            var enumType = enumValue.GetType();
            return Enum.GetValues(enumType)
                .Cast()
                .ToDictionary(t => (int)(object)t, t => t.ToString());
        }
    

提交回复
热议问题