enum to dictionary in c#

38 Points
14 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: 5788
Total Answered: 2
Total Marked As Answer: 1
Posted On: 29-May-2019 09:35

Share:   fb twitter linkedin
294 Points
82 Posts

Use following code

var dict1 = Enum.GetValues(typeof(niceEnum))
               .ToDictionary(t => t.ToString(), t => (int)t );
Posted On: 31-May-2019 07:24
738 Points
154 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))
               .ToDictionary(t => t.ToString(), t => (int)t );
Posted On: 21-Jun-2019 10:02
 Log In to Chat