Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Enums to Key,Value Pairs

Tags:

c#

How to convert Enum to Key,Value Pairs. I have converted it in C# 3.0 .

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

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

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

In C# 1.0 What is the way to do so?

like image 449
user193276 Avatar asked Oct 21 '09 08:10

user193276


People also ask

Is enum a key value pair?

An enum-like class that supports flags (up to 8192), has additional value-type data, description, and FastSerializer support.

Can enums be derived?

Nope. it is not possible. Enum can not inherit in derived class because by default Enum is sealed.

Can enums be changed?

Enum constants are final but it's variable can still be changed. For example, we can use setPriority() method to change the priority of enum constants. We will see it in usage in below example. Since enum constants are final, we can safely compare them using “==” and equals() methods.


2 Answers

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);
}
like image 52
jamie Avatar answered Sep 20 '22 01:09

jamie


I didn't read the question carefully, so my code will not work in C# 1.0 as it utilises generics. Best use it with >= C# 4.0 (>= VS2010)

To make life easier, I've created this helper service.

The usage for the service is as follows:

// create an instance of the service (or resolve it using DI)
var svc = new EnumHelperService();

// call the MapEnumToDictionary method (replace TestEnum1 with your enum)
var result = svc.MapEnumToDictionary<TestEnum1>();

The service code is as follows:

/// <summary>
/// This service provides helper methods for enums.
/// </summary>
public interface IEnumHelperService
{
    /// <summary>
    /// Maps the enum to dictionary.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    Dictionary<int, string> MapEnumToDictionary<T>();
}

/// <summary>
/// This service provides helper methods for enums.
/// </summary>
/// <seealso cref="Panviva.Status.Probe.Lib.Services.IEnumHelperService" />
public class EnumHelperService : IEnumHelperService
{
    /// <summary>
    /// Initializes a new instance of the <see cref="EnumHelperService"/> class.
    /// </summary>
    public EnumHelperService()
    {

    }

    /// <summary>
    /// Maps the enum to dictionary.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    /// <exception cref="System.ArgumentException">T must be an enumerated type</exception>
    public Dictionary<int, string> MapEnumToDictionary<T>() 
    {
        // Ensure T is an enumerator
        if (!typeof(T).IsEnum)
        {
            throw new ArgumentException("T must be an enumerator type.");
        }

        // Return Enumertator as a Dictionary
        return Enum.GetValues(typeof(T)).Cast<T>().ToDictionary(i => (int)Convert.ChangeType(i, i.GetType()), t => t.ToString());
    }
}
like image 22
Rohit L Avatar answered Sep 23 '22 01:09

Rohit L