Enum to dictionary

前端 未结 5 1366
南方客
南方客 2020-12-15 16:37

I want to implement an extension method which converts an enum to a dictionary:

public static Dictionary ToDictionary(this Enum @enum)
{
           


        
5条回答
  •  温柔的废话
    2020-12-15 17:13

    Here is the extension method I use to convert enumerations. The only difference is that I am returning IEnumerbale> for my purpose:

    public static IEnumerable> ToListOfKeyValuePairs(this TEnum enumeration) where TEnum : struct
    {
        return from TEnum e in Enum.GetValues(typeof(TEnum))
                select new KeyValuePair
                    (
                        (int)Enum.Parse(typeof(TEnum), e.ToString()),
                        Regex.Replace(e.ToString(), "[A-Z]", x => string.Concat(" ", x.Value[0])).Trim()
                    );
    }
    

    It also adds spaces for the value.

    Example:

    enum Province
    {
        BritishColumbia = 0,
        Ontario = 1
    }
    

    Usage:

    
    

    Output:

    
    

    Though @Paul Ruane is correct I have found this to be a very useful extension method. It's not a perfect world.

提交回复
热议问题