Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Iterate Over Enumeration Values in C#

DZone's Guide to

Iterate Over Enumeration Values in C#

·
Free Resource
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>.

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.

 

Topics:

Published at DZone with permission of Toni Petrina, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}