Enum to Dictionary in C#

前端 未结 10 2026
攒了一身酷
攒了一身酷 2020-12-02 15:10

I have searched this online, but I can\'t find the answer I am looking for.

Basically I have the following enum:

public enum typFoo : int
{
   itemA         


        
10条回答
  •  -上瘾入骨i
    2020-12-02 15:43

    Adapting Ani's answer so that it can be used as a generic method (thanks, toddmo):

    public static Dictionary EnumDictionary()
    {
        if (!typeof(T).IsEnum)
            throw new ArgumentException("Type must be an enum");
        return Enum.GetValues(typeof(T))
            .Cast()
            .ToDictionary(t => (int)(object)t, t => t.ToString());
    }
    

提交回复
热议问题