One for the utility library...
Here's a small function I've found to be quite useful recently. It takes an enum type and returns a generic list populated with each enum item.
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;
}
Here's one of the ways that I've used it:
List<DayOfWeek> weekdays =
EnumHelper.EnumToList<DayOfWeek>().FindAll(
delegate (DayOfWeek x)
{
return x != DayOfWeek.Sunday && x != DayOfWeek.Saturday;
});
Posted
10-10-2006 11:40 AM
by
Joe Niland