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;

Random Enumeration Generator with Generics


public static I RandomEnumeration<I>()
{
  I enumerationToCheck;
  Int32 indexToUse;
  String[] names;

  //Use activator to create an instance of the type I
  enumerationToCheck = System.Activator.CreateInstance<I>();

  //Make sure the instance is an Enumeration
   //Unfortunately you can't check that in the method 
   //delcaring using "which".
  if (enumerationToCheck as Enum == null)
  {
    throw new InvalidOperationException();
  }

  //Get the list of the enumeration item names
  names = Enum.GetNames(typeof(I));

  if (names.Length > 0)
  {
    //Grab a random name within the boundaries of the
     //names collection.
    indexToUse = RandomInt32(0, names.Length);
    //parse the name to create the random enum
    enumerationToCheck = (I)Enum.Parse(typeof(I), names[indexToUse]);
  }

  return enumerationToCheck;

}

Usage:


  SomeEnum test = RandomEnumeration();

Why bother? For unit testing and creating test classes. Possibly
for defaults on an enumeration, but not really needed since
they are value types. Oh yeah AND BECAUSE I FELT LIKE IT. I don’t
have to explain myself to you.