Enum to Dictionary in C#

前端 未结 10 2034
攒了一身酷
攒了一身酷 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: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:

        
    

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

提交回复
热议问题