Represent an enumeration as a sequence

There is a nice way to represent an arbitrary enumeration as a sequence of its names, values or name/value pairs. To do this we have to use extension methods:

using System;
using System.Linq;
using System.Collections.Generic;

/// <summary>
/// Contains extension method on the <see cref="System.Type"/> allowing to represent
/// an enumeration members as a sequence.
/// </summary>
public static class EnumExtensions
{
    /// <summary>
    /// Get values of the specified enumeration type.
    /// </summary>
    /// <param name="type">Extendee type.</param>
    /// <returns>The sequence of values of the enumeration specified.</returns>
    public static IEnumerable<object> Values(this Type type)
    {
        Type enumType = Nullable.GetUnderlyingType(type) ?? type;
        if (!enumType.IsEnum)
            yield break;

        foreach (object item in Enum.GetValues(enumType))
            yield return Convert.ChangeType(item, Enum.GetUnderlyingType(enumType));
    }

    /// <summary>
    /// Get names of the specified enumeration type.
    /// </summary>
    /// <param name="type">Extendee type.</param>
    /// <returns>The sequence of names of the enumeration specified.</returns>
    public static IEnumerable<string> Names(this Type type)
    {
        Type enumType = Nullable.GetUnderlyingType(type) ?? type;
        if (!enumType.IsEnum)
            yield break;

        foreach (string item in Enum.GetNames(enumType))
            yield return item;
    }

    /// <summary>
    /// Get name/value pairs of the specified enumeration type.
    /// </summary>
    /// <param name="type">Extendee type.</param>
    /// <returns>The sequence of name/value pairs of the enumeration specified.</returns>
    public static IEnumerable<KeyValuePair<string, object>> Dictionary(this Type type)
    {
        Type enumType = Nullable.GetUnderlyingType(type) ?? type;
        if (!enumType.IsEnum)
            yield break;

        IEnumerable<KeyValuePair<string, object>> dictionary =
            from value in Enum.GetValues(enumType).Cast<object>()
            select new KeyValuePair<string, object>(Enum.GetName(enumType, value)
                , Convert.ChangeType(value, Enum.GetUnderlyingType(enumType)));
        
        foreach (KeyValuePair<string, object> item in dictionary)
            yield return item;
    }
}

This could be useful when, for example, the task is to fill the contents of the ListBox or an another such control with the list of enumeration values.

In WPF, for example, if we have three list boxes which we’re going to fill with the values of System.UriPartial enumeration all we have to do is the following:

Type enumType = typeof(UriPartial);
lbxValues.ItemsSource = enumType.Values();
lbxNames.ItemsSource = enumType.Names();
lbxDictionary.ItemsSource = enumType.Dictionary();

and we’ll get the following picture:

I’m aware on other approaches to this task (see, for example, Accessing Enum members in Xaml by Andrew Smith or Binding and using Friendly enums in WPF by Sasha Barber), this is just the another one.

Cheers,
Oleg V. Polikarpotchkin

Technorati Теги: ,,,

Advertisements

About ovpwp

I am engaged in programming, maintenance and supply of computing technique since 1970. Started with the computers M, BESM, Minsk series and received appropriate education in the least, in which it was then possible in THE USSR. Then he went the usual way - ES series, IBM 360/370, Sun Spark, Ibm Power & PS2, PC. Programming started in the code (machine commands), then were sorts of assemblers, Algol, FORTRAN, PL/1, C, C , VB, C#. It is only the ones that I used the production scale; but there were, of course, others like List, Modula, Pascal, Java, etc. Currently I prefer .NET platform for desktop development. I don't really like web-programming (probably because of the inability for quality design), but I have enough experience in site building in LAMP environment using PHP.
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s