Using LINQ to foreach over an enum in C#
I can’t be the only person in the world who wants to foreach over the values of an enum otherwise Enum.GetValues(Type enumType) wouldn’t exist in the framework. Alas it didn’t get any generics love in .NET 2.0 and unhelpfully returns an array.
Thanks to the power of LINQ you can do this:
foreach(var customerType in Enum.GetValues(typeof(CustomerTypes)).Cast<CustomerTypes>()))
That is okay, but this is more concise:
foreach(CustomerTypes customerType in Enums.Get<CustomerTypes>())
The tiny class to achieve that is, of course:
using System.Collections.Generic;
using System.Linq;
public static class Enums {
public static IEnumerable<T> Get<T>() {
return System.Enum.GetValues(typeof(T)).Cast<T>();
}
}
Great.
[)amien
8 responses