Convert Enum to Dictionary: Another Silly Method

So what if you want the names and values from an Enum, but wanted them in dictionary form. Well shoot, a little bit of linq and little bit of that and you got this:

public static IDictionary<String, Int32> ConvertEnumToDictionary<K>()
{
 if (typeof(K).BaseType != typeof(Enum))
 {
   throw new InvalidCastException();
 }

 return Enum.GetValues(typeof(K)).Cast<Int32>().ToDictionary(currentItem => Enum.GetName(typeof(K), currentItem));
}

As you might see, pretty simple.

Ok so ToDictionary is kind of odd looking maybe, but really isn’t that big of a deal. Basically it assumes the items in the list are the value, but you need to tell it what the key is. In this case, the int values for the enum are the value for the dictionary where the name that matches said int value will become the key for the dictionary.

So basically, get the values for the enum. Turn that into an IEnumerable list of Int32, create a Dictionary from that.

USINGS!!111

 using System;
 using System.Collections.Generic;
 using System.Linq;

8 thoughts on “Convert Enum to Dictionary: Another Silly Method”

  1. public static Dictionary GetAccessLevelDictionary()
    {
    Dictionary accessLevels = new Dictionary();
    foreach (int value in System.Enum.GetValues(typeof(AccessLevel)))
    {
    accessLevels.Add(System.Enum.GetName(typeof(AccessLevel), value), value);
    }

    return accessLevels;
    }

    in this method ‘AccessLevel’ is Enum

  2. I got
    public static IDictionary ConvertEnumToDictionary()
    {
    if (typeof(K).BaseType != typeof(Enum))
    {
    throw new InvalidCastException();
    }

    return Enum.GetValues(typeof(K)).Cast().ToDictionary(currentItem => Enum.GetName(typeof(K), currentItem));
    }

    do you have a youtube video to help?

  3. This was not, and is not a silly method. Making your method an extension method, I just save myself 10 minutes in binding each enum to a UI drop-down. Thanks for your method.

Comments are closed.