Skip to content

enum to list in csharp

August 9, 2011
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;
}
Advertisement
No comments yet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.