Skip to main content

C# method to convert an Enum type to a Dictionary.

void Main()
{
	var items = EnumToDictionary<Suits>();
	
	foreach (var item in items)
	{
		Console.WriteLine($"Key: {item.Key}, Value: {item.Value}");
	}
}

public enum Suits
{
	Spades = 0,
	Hearts = 1,
	Clubs = 2,
	Diamonds = 4,
	NumSuits = 8
}

public static Dictionary<int, string> EnumToDictionary<T>() where T : struct
{
	if (!typeof(T).IsEnum)
		throw new ArgumentException("T is not an Enum type");

	return Enum.GetValues(typeof(T))
		.Cast<object>()
		.ToDictionary(k => (int)k, v => v.ToString());
}