开发者

Converting Enums to Key,Value Pairs

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?


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);
}


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?


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>()


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());
    }
}


Enum.GetValues(typeof(DirectionEnum)).Cast<int>().Select(p => new { id = p,name=((DirectionEnum)p).ToString() }).ToList();


Borrowing from the answer by @jamie

Place this into a static extension class then do typeof(Translation).ToValueList<int>();

    /// <summary>
    /// If an enum MyEnum is { a = 3, b = 5, c = 12 } then
    /// typeof(MyEnum).ToValueList<<int>>() will return [3, 5, 12]
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="enumType"></param>
    /// <returns>List of values defined for enum constants</returns>
    public static List<T> ToValueList<T>(this Type enumType)
    {
        return Enum.GetNames(enumType)
            .Select(x => (T)Enum.Parse(enumType, x))
            .ToList();
    }


Here's my version. Feels more straightforward to me than any of the suggestions above but maybe I'm missing something:

Enum.GetValues<SomeEnum>().Select(g => new KeyValuePair<int, string>((int)g, g.ToString()));


var enumType = typeof(Translation);
var objList = enumValuesList.Select(v =>
{
    var i =  (Translation)Enum.Parse(enumType, v);
    return new
    {
        Id = (int)i,
        Value = v
    };
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜