1
I need to return a List Selectlistitem where the value property of each item returns the value of Enum (1, 2...) and not the name of the property (physical, juridical...). How do I do that?
Function
public static IEnumerable<SelectListItem> EnumParaSelectListGenericoNumerico<T>(string tipoCase = null)
{
var teste = (Enum.GetValues(typeof(T)).Cast<T>().Select(
e => new SelectListItem()
{
Text = (tipoCase == null ? ObterDescricaoEnumGenerico<T>(e.ToString()) : (tipoCase.ToUpper() == "U" ? ObterDescricaoEnumGenerico<T>(e.ToString()).ToUpper() : ObterDescricaoEnumGenerico<T>(e.ToString()))),
Value = e.ToString()
}
)).ToList();
return teste;
}
Auxiliary function
public static string ObterDescricaoEnumGenerico<T>(string value)
{
Type type = typeof(T);
var name = Enum.GetNames(type).Where(f => f.Equals(value, StringComparison.CurrentCultureIgnoreCase)).Select(d => d).FirstOrDefault();
if (name == null)
{
return string.Empty;
}
var field = type.GetField(name);
var customAttribute = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
return customAttribute.Length > 0 ? ((DescriptionAttribute)customAttribute[0]).Description : name;
}
Function call
sistemaViewModel.PessoasNaturezas = ExtensaoDeEnumerador.EnumParaSelectListGenericoNumerico<PessoaNatureza>("U").OrderBy(x => x.Text);
Enum
public enum PessoaNatureza
{
[Description("FÍSICA")]
Fisica = 1,
[Description("JURÍDICA")]
Juridica = 2
}
can’t give an e.gethashcode()?
– Lucas Miranda
It worked brtother @Lucas Miranda!!! comments as reply in the post I set as answered. Thank you )
– Master JR