Looking for simplier or shorter way to convert enum description attributes to a list
Sure there is a better way to accomplish this. Perhaps with a linq statement?
Im wanting to geta a list of all the descriptions on the enum which will be thrown into a dropdown in grid column
I cant just go by teh names and convert to a string as I have a situation where there is a "blank" and no way to represent that as a named enum member which is a valid option
Thanks
Code:
//Controller
[HttpGet]
public JsonResult GetPriorities([DataSourceRequest]DataSourceRequest request)
{
List<string> model = new List<string>();
List<CaseParty.PRIORITY_TYPE> enm = Enum.GetValues(typeof(CaseParty.PRIORITY_TYPE)).Cast<CaseParty.PRIORITY_TYPE>().ToList();
foreach (CaseParty.PRIORITY_TYPE en in enm)
{
string attrib = en.ToDescriptionString();
model.Add(attrib);
}
return Json(model, JsonRequestBehavior.AllowGet);
}
Code:
//Extension method
public static string ToDescriptionString(this Enum This)
{
Type type = This.GetType();
string name = Enum.GetName(type, This);
MemberInfo member = type.GetMembers().Where(w => w.Name == name).FirstOrDefault();
DescriptionAttribute attribute = member != null ? member.GetCustomAttributes(true).Where(w => w.GetType() == typeof(DescriptionAttribute))
.FirstOrDefault() as DescriptionAttribute : null;
return attribute != null ? attribute.Description : name;
}
Code:
//ENUM
public enum PRIORITY_TYPE
{
[Description(" ")]
BLANK,
[Description("A")]
A,
[Description("B")]
B,
[Description("C")]
C
}
Re: Looking for simplier or shorter way to convert enum description attributes to a l
The code is not necessarily shorter overall but check out these classes I created for this purpose:
http://www.vbforums.com/showthread.php?552563
In your case, the code would be:
csharp Code:
var model = new EnumDescriptorCollection<CaseParty.PRIORITY_TYPE>().Select(ed => ed.ToString()).ToList();
That said, you could already be using this:
csharp Code:
var model = Enum.GetValues(typeof(CaseParty.PRIORITY_TYPE))
.Cast<CaseParty.PRIORITY_TYPE>()
.Select(pt => pt.ToDescriptionString())
.ToList();