Thursday, August 14, 2008

Another silly method just for you

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;

No comments: