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

EnumToDictionary<T>

Enum to Dictionary

Source

/// <summary>
/// usage Dictionary<int,string> ad = ITMS.Helper.EnumToDictionary<AreaTypes>();
/// </summary>
/// <typeparam name="T">Must be ENum</typeparam>
/// <returns>Dictionary<int,string></returns>
public static Dictionary<int,string> EnumToDictionary<T>()
{
    Type enumType = typeof (T);
    // Can't use type constraints on value types
    if (enumType.BaseType != typeof(Enum))
        throw new ArgumentException("T must be of type System.Enum");
    
    Dictionary<int,string> dic = new Dictionary<int,string>();
    foreach (string val in Enum.GetNames(enumType)) 
    {
        dic.Add((int)Enum.Parse(enumType,val), val);
    }
    return dic;
}

Example

Dictionary<int,string> ad = ITMS.Helper.EnumToDictionary<AreaTypes>();

Author: endstreet

Submitted on: 13 nov 2019

Language: csharp

Type: Enum

Views: 116