Friday, January 21, 2011

Generic Enum to List converter (C#)

Sometimes it is necessary to take enumerations and bind them to some kind of UI control requiring a list. There are various ways to do this, but after some research nobody had included a solution that has the numeric index of the enumeration. The code below shows this implementation, which involves a class of type EnumItem (to store invidivual enum values) and a static conversion function EnumToList, which does the work :

///
/// Generic EnumItem class for Enum item representation.
///

public class EnumItem
{
///
/// The enum index, it is a 1-based index.
///

/// The enum index value (1-based).
public int Index { get; set; }

public string Name { get; set; }
public object Value { get; set; }
}

///
/// Converts an Enum to a List of type EnumItem.
///

/// The type of enum to convert.
/// List of type EnumItem.
public static List EnumToList()
{
//Validate T is an enum
Type enumType = typeof(T);
if (enumType.BaseType != typeof(Enum))
{
throw new ArgumentException("T must be of type System.Enum");
}

var valueArray = (T[])(Enum.GetValues(typeof(T)).Cast());
var nameArray = Enum.GetNames(typeof(T)).ToArray();
List enumItemList = new List();
for (int i = 0; i < valueArray.Length; i++)
{
string name = nameArray[i];
T value = valueArray[i];
enumItemList.Add(new EnumItem { Index = i + 1, Name = name, Value = value });
}
return enumItemList;
}


By calling List myList = EnumToList() you will receive a 3-column list containing the 1-based index, the enum name, and the enum value.