Over a million developers have joined DZone.

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>.

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.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}