I want to implement an extension method which converts an enum to a dictionary:
public static Dictionary ToDictionary(this Enum @enum)
{
Here is the extension method I use to convert enumerations. The only difference is that I am returning IEnumerbale
public static IEnumerable> ToListOfKeyValuePairs(this TEnum enumeration) where TEnum : struct
{
return from TEnum e in Enum.GetValues(typeof(TEnum))
select new KeyValuePair
(
(int)Enum.Parse(typeof(TEnum), e.ToString()),
Regex.Replace(e.ToString(), "[A-Z]", x => string.Concat(" ", x.Value[0])).Trim()
);
}
It also adds spaces for the value.
Example:
enum Province
{
BritishColumbia = 0,
Ontario = 1
}
Usage:
Output:
Though @Paul Ruane is correct I have found this to be a very useful extension method. It's not a perfect world.