Skip to content

Instantly share code, notes, and snippets.

@gavilanch
Created October 8, 2016 20:05
Show Gist options
  • Save gavilanch/884f43f0c75b1cbebb0628cab005d456 to your computer and use it in GitHub Desktop.
Save gavilanch/884f43f0c75b1cbebb0628cab005d456 to your computer and use it in GitHub Desktop.
public List<SelectListItem> ToListSelectListItem<T>()
{
var t = typeof(T);
if (!t.IsEnum) { throw new ApplicationException("Tipo debe ser enum"); }
var members = t.GetFields(BindingFlags.Public | BindingFlags.Static);
var result = new List<SelectListItem>();
foreach (var member in members)
{
var attributeDescription = member.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute),
false);
var descripcion = member.Name;
if (attributeDescription.Any())
{
descripcion = ((System.ComponentModel.DescriptionAttribute)attributeDescription[0]).Description;
}
var valor = ((int)Enum.Parse(t, member.Name));
result.Add(new SelectListItem()
{
Text = descripcion,
Value = valor.ToString()
});
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment