enum to dictionary in c#

kikme
kikme
26 Points
8 Posts

I'm using asp.net core to develop REST API and I have few enum values that to be expose to API response. And I'm able to do that but client developer don't know what are the enum's values. So I want to expose all enum values in the response.

Suppose I have following enum:

public enum niceEnum
{
   itemA = 1,
   itemB = 2,
   itemC = 3
}

And wan to show in response as:

1, itemA
2, itemB
3, itemC

How we can do this using dictionary?

Views: 207
Total Answered: 2
Total Marked As Answer: 1
Posted On: 29-May-2019 09:35

Share:   fb twitter linkedin
Answers
beginer
beginer
100 Points
35 Posts
         

Use following code

var dict1 = Enum.GetValues(typeof(niceEnum))
               .Cast<niceEnum>()
               .ToDictionary(t => t.ToString(), t => (int)t );
Posted On: 31-May-2019 07:24
Smith
Smith
Participant
390 Points
115 Posts
         

Following is an Enum extension that converts it to a Dictionary:

Dictionary<Int32, String> dt = niceEnum.ToDictionary();
public static Dictionary<int, string> ToDictionary(this Enum value)
{
   return Enum.GetValues(typeof(value))
               .Cast<value>()
               .ToDictionary(t => t.ToString(), t => (int)t );
}
Posted On: 21-Jun-2019 10:02
 Log In to Chat