[C#] 將列舉轉換為 SelectListItem 下拉選單 (Enum To SelectListItem)
實作 1. 列舉內容 public enum TestEnum { [Display(Name = "A", Description = "A")] A, [Display(Name = "B", Description = "B")] B } 2. 建立一個 Enum-Helper /// <summary> /// Enum-Helper /// </summary> public static class EnumHelper { /// <summary> /// 轉換為 SelectListItem 下拉選單 /// </summary> /// <returns></returns> public static IEnumerable<SelectListItem> ToSelectListItem<T>() where T : struct { var type = typeof(T); if (!type.IsEnum) { return null; } var result = Enum.GetValues(type) .Cast () .Select(x => new SelectListItem { Value = (x.ToInt()).ToString(), Text =$"Name:{x.GetN