How to return the numeric value of a Selectlistitem C#

Asked

Viewed 64 times

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?

inserir a descrição da imagem aqui

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()?

  • It worked brtother @Lucas Miranda!!! comments as reply in the post I set as answered. Thank you )

1 answer

0


As commented, just use the command getHashCode, example:

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.GetHashCode()
        }
        )).ToList();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.