ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

EnumToDictionary

Converts an Enumeration type into a dictionary of its names and values.

Source

/// <summary>
/// Converts Enumeration type into a dictionary of names and values
/// </summary>
/// <param name="t">Enum type</param>
public static IDictionary<string, int> EnumToDictionary(this Type t)
{
    if (t == null) throw new NullReferenceException();
    if (!t.IsEnum) throw new InvalidCastException("object is not an Enumeration");

    string[] names = Enum.GetNames(t);
    Array values = Enum.GetValues(t);

    return (from i in Enumerable.Range(0, names.Length)
            select new { Key = names[i], Value = (int)values.GetValue(i) })
                .ToDictionary(k => k.Key, k => k.Value);
}

Example

var dictionary = typeof(UriFormat).EnumToDictionary();

/* returns
key => value
SafeUnescaped => 3
Unescaped => 2
UriEscaped => 1
*/

Author: Daniel Gidman

Submitted on: 3 dec. 2010

Language: C#

Type: System.Type

Views: 9325