C# 将枚举转换为键值对
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1599386/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting Enums to Key,Value Pairs
提问by user193276
How to convert Enum to Key,Value Pairs. I have converted it in C# 3.0.
如何将枚举转换为键值对。我已将其转换为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.0What is the way to do so?
在C# 1.0中这样做的方法是什么?
采纳答案by Jon Skeet
In C# 1...
在 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 indexto name though? If you're just using integer indexes, why not just use an array or an ArrayList
?
你确定你真的想要一张从索引到名字的映射吗?如果您只是使用整数索引,为什么不只使用数组或一个ArrayList
?
回答by jamie
For C# 3.0 if you have an Enum like this:
对于 C# 3.0,如果您有这样的 Enum:
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);
}
回答by Castilho2
var enumType = typeof(Translation);
var objList = enumValuesList.Select(v =>
{
var i = (Translation)Enum.Parse(enumType, v);
return new
{
Id = (int)i,
Value = v
};
});
回答by Ro Hit
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)
我没有仔细阅读问题,因此我的代码在 C# 1.0 中无法使用,因为它使用了泛型。最好与 >= 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());
}
}
回答by abbaf33f
Borrowing from the answer by @jamie
借用@jamie 的回答
Place this into a static extension class then do
typeof(Translation).ToValueList<int>();
把它放到一个静态扩展类中然后做
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();
}