Iterate Over Enumeration Values in C#
This is just a small method that allows iterating over enumeration
values. I needed strong type and LINQ support for enumeration values,
but the built-in method returns Array which is unusable. You have to convert each value to the enumeration type using Cast<T>.
Published at DZone with permission of Toni Petrina, author and DZone MVB. (source)The generator function is given as:
static class EnumEx
{
public static IEnumerable<T> GetValues<T>()
{
foreach (T value in Enum.GetValues(typeof(T)))
{
yield return value;
}
}
}You can use it in the following manner:
foreach (var value in EnumEx.GetValues<someEnum>())
{
// ...
}The official way to achieve the above functionality with built in stuff in .NET 4 is using the following not-so-short code:
foreach (var value in typeof(enumStructureParameters)
.GetEnumValues()
.Cast<enumStructureParameters>())
{
// ...
}Happy coding.
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)





