1. 程式人生 > >C# Enum列舉轉 Dictionary字典

C# Enum列舉轉 Dictionary字典

方法1

Dictionary<int, string> mydic = new Dictionary<int, string>();

foreach (EnumName foo in Enum.GetValues(typeof(EnumName)))
{
    mydic.Add((int)foo, foo.ToString());
}

方法2

var dict = Enum.GetValues(typeof(EnumName))
               .Cast<EnumName>()
               .ToDictionary
(t => (int)t, t => t.ToString());

方法3

/// <summary>
/// 列舉轉字典集合(Key是value,Value是description(如果不存在description 則是name))
/// </summary>
/// <typeparam name="T">列舉類名稱</typeparam>
/// <param name="keyDefault">預設key值</param>
/// <param name="valueDefault">預設value值</param>
/// <returns>返回生成的字典集合</returns> public static Dictionary<string, object> EnumListDic<T>(string keyDefault, string valueDefault = "") { Dictionary<string, object> dicEnum = new Dictionary<string, object>(); Type enumType = typeof(T); if (!enumType.IsEnum) { return
dicEnum; } if (!string.IsNullOrEmpty(keyDefault)) //判斷是否新增預設選項 { dicEnum.Add(keyDefault, valueDefault); } string[] fieldstrs = Enum.GetNames(enumType); //獲取列舉欄位陣列 foreach (var item in fieldstrs) { string description = string.Empty; var field = enumType.GetField(item); object[] arr = field.GetCustomAttributes(typeof(DescriptionAttribute), true); //獲取屬性欄位陣列 if (arr != null && arr.Length > 0) { description = ((DescriptionAttribute)arr[0]).Description; //屬性描述 } else { description = item; //描述不存在取欄位名稱 } dicEnum.Add(description, (int)Enum.Parse(enumType, item)); //不用列舉的value值作為字典key值的原因從列舉例子能看出來,其實這邊應該判斷他的值不存在,預設取欄位名稱 } return dicEnum; }