Enum to Dictionary in C#

前端 未结 10 2008
攒了一身酷
攒了一身酷 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<int, string> ConvertToDictionary<T>() where T : struct
        {
            var dictionary = new Dictionary<int, string>();
    
            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<typFoo>();
    
    0 讨论(0)
  • 2020-12-02 15:55

    If you need only the name you don't have to create that dictionary at all.

    This will convert enum to int:

     int pos = (int)typFoo.itemA;
    

    This will convert int to enum:

      typFoo foo = (typFoo) 1;
    

    And this will retrun you the name of it:

     ((typFoo) i).toString();
    
    0 讨论(0)
  • 2020-12-02 15:56

    +1 to Ani. Here's the VB.NET version

    Here's the VB.NET version of Ani's answer:

    Public Enum typFoo
        itemA = 1
        itemB = 2
        itemC = 3
    End Enum
    
    Sub example()
    
        Dim dict As Dictionary(Of Integer, String) = System.Enum.GetValues(GetType(typFoo)) _
                                                     .Cast(Of typFoo)() _
                                                     .ToDictionary(Function(t) Integer.Parse(t), Function(t) t.ToString())
        For Each i As KeyValuePair(Of Integer, String) In dict
            MsgBox(String.Format("Key: {0}, Value: {1}", i.Key, i.Value))
        Next
    
    End Sub
    

    Additional example

    In my case, I wanted to save the path of important directories and store them in my web.config file's AppSettings section. Then I created an enum to represent the keys for these AppSettings...but my front-end engineer needed access to these locations in our external JavaScript files. So, I created the following code-block and placed it in our primary master page. Now, each new Enum item will auto-create a corresponding JavaScript variable. Here's my code block:

        <script type="text/javascript">
            var rootDirectory = '<%= ResolveUrl("~/")%>';
            // This next part will loop through the public enumeration of App_Directory and create a corresponding JavaScript variable that contains the directory URL from the web.config.
            <% Dim App_Directories As Dictionary(Of String, App_Directory) = System.Enum.GetValues(GetType(App_Directory)) _
                                                                       .Cast(Of App_Directory)() _
                                                                       .ToDictionary(Of String)(Function(dir) dir.ToString)%>
            <% For Each i As KeyValuePair(Of String, App_Directory) In App_Directories%>
                <% Response.Write(String.Format("var {0} = '{1}';", i.Key, ResolveUrl(ConfigurationManager.AppSettings(i.Value))))%>
            <% next i %>
        </script>
    

    NOTE: In this example, I used the name of the enum as the key (not the int value).

    0 讨论(0)
  • 2020-12-02 15:59

    Try:

    var dict = Enum.GetValues(typeof(fooEnumType))
                   .Cast<fooEnumType>()
                   .ToDictionary(t => (int)t, t => t.ToString() );
    
    0 讨论(0)
提交回复
热议问题