2013-10-11 84 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));