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;
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
Would I be able to add this code in my wordpress?
That’d be awesome!
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?
What’s the issue you’re running into?
Are there youtube videos to help fix this problem?
I’d love to be able to fix the problem myself, but its taking up too much time
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.
Appreciate the appreciation.