Enum to Dictionary in C#

前端 未结 10 2040
攒了一身酷
攒了一身酷 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条回答
  •  死守一世寂寞
    2020-12-02 15:54

    Use:

    public static class EnumHelper
    {
        public static IDictionary ConvertToDictionary() where T : struct
        {
            var dictionary = new Dictionary();
    
            var values = Enum.GetValues(typeof(T));
    
            foreach (var value in values)
            {
                int key = (int) value;
    
                dictionary.Add(key, value.ToString());
            }
    
            return dictionary;
        }
    }
    

    Usage:

    public enum typFoo : int
    {
       itemA = 1,
       itemB = 2,
       itemC = 3
    }
    
    var mydic = EnumHelper.ConvertToDictionary();
    

提交回复
热议问题