Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum to dictionary

Tags:

c#

.net

I want to implement an extension method which converts an enum to a dictionary:

public static Dictionary<int, string> ToDictionary(this Enum @enum) {     Type type1 = @enum.GetType();     return Enum.GetValues(type1).Cast<type1>()         //.OfType<typeof(@enum)>()         .ToDictionary(e => Enum.GetName(@enum.GetType(), e)); } 

Why it doesn't compile?

An error:

"The type or namespace name 'type1' could not be found (are you missing a using directive or an assembly reference?)"

like image 540
Alexandre Avatar asked Mar 31 '11 12:03

Alexandre


People also ask

Is an enum a dictionary?

Dictionaries store unordered collections of values of the same type, which can be referenced and looked up through a unique identifier (also known as a key). An enumeration defines a common type for a group of related values and enables you to work with those values in a type-safe way within your code.

Does Python have enums?

Enum is a class in python for creating enumerations, which are a set of symbolic names (members) bound to unique, constant values. The members of an enumeration can be compared by these symbolic anmes, and the enumeration itself can be iterated over.

What is enum in C#?

An enumeration type (or enum type) is a value type defined by a set of named constants of the underlying integral numeric type. To define an enumeration type, use the enum keyword and specify the names of enum members: C# Copy. enum Season { Spring, Summer, Autumn, Winter }


1 Answers

Jon Skeet has written everything you need ;)

But here you have your code that is working:

public static Dictionary<int, string> ToDictionary(this Enum @enum) {   var type = @enum.GetType();   return Enum.GetValues(type).Cast<int>().ToDictionary(e => e, e => Enum.GetName(type, e)); } 
like image 108
Rafal Spacjer Avatar answered Sep 22 '22 06:09

Rafal Spacjer