Converting Enums to Key,Value Pairs

I think, this example will help to you.

For example your enum defined like as below:

public enum Translation
{
    English,
    Russian,
    French,
    German
}

You can use this below code piece for convert enum to KeyValuePairs:

var translationKeyValuePairs = Enum.GetValues(typeof(Translation))
                                   .Cast<int>()
                                   .Select(x => new KeyValuePair<int, string>(key: x, value: Enum.GetName(typeof(Translation), x)))
                                   .ToList();

Or you can use Dictionary like as below:

var translationDictionary = Enum.GetValues(typeof(Translation))
                                .Cast<int>()
                                .ToDictionary(enumValue => enumValue, 
                                              enumValue => Enum.GetName(typeof(Translation), enumValue));

Note: If your enum's type isn't int, for example it enum's type is byte, you may use Cast<byte>() instead of Cast<int>()


In C# 1...

string[] names = Enum.GetNames(typeof(Translation));

Hashtable hashTable = new Hashtable();
for (int i = 0; i < names.Length; i++)
{
    hashTable[i + 1] = names[i];
}

Are you sure you really want a map from index to name though? If you're just using integer indexes, why not just use an array or an ArrayList?


For C# 3.0 if you have an Enum like this:

public enum Translation
{
    English = 1,
    Russian = 2,
    French = 4,
    German = 5
}

don't use this:

string[] trans = Enum.GetNames(typeof(Translation));

var v = trans.Select((value, key) =>
new { value, key }).ToDictionary(x => x.key + 1, x => x.value);

because it will mess up your key (which is an integer).

Instead, use something like this:

var dict = new Dictionary<int, string>();
foreach (var name in Enum.GetNames(typeof(Translation)))
{
    dict.Add((int)Enum.Parse(typeof(Translation), name), name);
}

Tags:

C#