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?)"
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.
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.
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 }
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)); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With