[英]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.