[英]Create a dictionary from enum values
我有以下枚举:
public enum Brands
{
HP = 1,
IBM = 2,
Lenovo = 3
}
从中我想以以下格式制作字典:
// key = name + "_" + id
// value = name
var brands = new Dictionary<string, string>();
brands[HP_1] = "HP",
brands[IBM_2] = "IBM",
brands[Lenovo_3] = "Lenovo"
到目前为止,我已经做到了,但是从方法创建字典有困难:
public static IDictionary<string, string> GetValueNameDict<TEnum>()
where TEnum : struct, IConvertible, IComparable, IFormattable
{
if (!typeof(TEnum).IsEnum)
throw new ArgumentException("TEnum must be an Enumeration type");
var res = from e in Enum.GetValues(typeof (TEnum)).Cast<TEnum>()
select // couldn't do this
return res;
}
谢谢!
您可以使用Enumerable.ToDictionary()创建字典。
不幸的是,编译器不允许我们将TEnum强制转换为int,但是由于您已经断言该值为Enum,因此我们可以安全地将其强制转换为一个对象,然后是int。
var res = Enum.GetValues(typeof(TEnum)).Cast<TEnum>().ToDictionary(e => e + "_" + (int)(object)e, e => e.ToString());
//使用以下代码:
Dictionary<string, string> dict = Enum.GetValues(typeof(Brands)).Cast<int>().ToDictionary(ee => ee.ToString(), ee => Enum.GetName(typeof(Brands), ee));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.