2013-10-11 83 views
1

我有以下枚举:创建字典从枚举值

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

谢谢!

回答

6

您可以使用Enumerable.ToDictionary()创建你的字典。

不幸的是,编译器不会让我们投了TEnum为int,而是因为你已经断言,值是一个枚举,我们可以放心地将其转换为对象,然后一个int。

var res = Enum.GetValues(typeof(TEnum)).Cast<TEnum>().ToDictionary(e => e + "_" + (int)(object)e, e => e.ToString()); 
2

//使用这个代码:

Dictionary<string, string> dict = Enum.GetValues(typeof(Brands)).Cast<int>().ToDictionary(ee => ee.ToString(), ee => Enum.GetName(typeof(Brands), ee));