Tuesday, August 9, 2011

convert enum to list in csharp

This function will convert any enum to a List object

public class EnumHelper
{
/// < summary >
/// Convert enum to a list object.
/// < /summary >
/// < typeparam name="T" >< /typeparam >
/// < returns >< /returns >
public static List< T > EnumToList< T >()
{
Type enumType = typeof(T);

// You can't use type constraints on value types, so have to check & throw error.
if (enumType.BaseType != typeof(Enum))
throw new ArgumentException("T must be of type System.Enum type");

Array enumValArray = Enum.GetValues(enumType);

List< T > enumValList = new List< T >(enumValArray.Length);

foreach (int val in enumValArray)
{
enumValList.Add((T)Enum.Parse(enumType, val.ToString()));
}

return enumValList;
}






// Now call the function with enum you want to conver into a list EnumHelper.EnumToList< EventState >()

public static List < EventState > GetEventStates()
{
List< EventState > eventStates = EnumHelper.EnumToList< EventState >();
//.FindAll(
//delegate(EventState x)
//{
// return x != EventState.Cancelled ;
//});
return eventStates;
}