ExtensionMethod.NET Home of 818 C#, Visual Basic, F# and Javascript extension methods

Generic Enum to List<T> converter

http://devlicio.us/blogs/joe_niland/archive/2006/10/10/Generic-Enum-to-List_3C00_T_3E00_-converter.aspx

Source

public static List<T> EnumToList<T>()
{
    Type enumType = typeof (T);

    // Can't use type constraints on value types, so have to do check like this
    if (enumType.BaseType != typeof(Enum))
        throw new ArgumentException("T must be of type System.Enum");
    
    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;
}

Example

List<DayOfWeek> weekdays =
    EnumHelper.EnumToList<DayOfWeek>().FindAll(
delegate (DayOfWeek x)
{
    return x != DayOfWeek.Sunday && x != DayOfWeek.Saturday;
});

Author: Joe Niland

Submitted on: 16 okt 2010

Language: C#

Type: System.Enum

Views: 11430