Compare string to Enum, inside the lambda?

Asked

Viewed 712 times

1

the problem is:

I have a dropdownlist loaded from an Enum, which can come with the null value of the screen.

listaItensSolicitados = os.Site == null ? 
   this.itemSolicitadoService.Consultar(o =>
            o.ItemServico.Servico.Chave == 9 &&
            o.ChaveOrgao == os.Orgao.Chave && o.Numero.Contains(ramal)
            && o.CategoriaDiurna == ddlCategoriaDiurna
            && o.Instalado == true
            && (o.Depreciado == null
            || o.Depreciado == false)).Take(200).ToList() :

As you know, you can’t use ToString() within the lambda, I wonder if there’s a way I can make that comparison, in my ActionResult i get from the screen the value of DDL as string, and when comes the value null, doesn’t work.

@Edit

This is my enum:

public enum CategorizacaoRamaisEnum : int
{     
    [Description("Categoria 1")]
    Categoria1 = 1,
    [Description("Categoria 2")]
    Categoria2,
    [Description("Categoria 3")]
    Categoria3,
    [Description("Categoria 4")]
    Categoria4,
    [Description("Categoria 5")]
    Categoria5,
    [Description("Categoria 6")]
    Categoria6,
    [Description("Categoria 7")]
    Categoria7,
    [Description("Categoria 8")]
    Categoria8,
    [Description("Categoria 9")]
    Categoria9,
    [Description("Categoria 10")]
    Categoria10,
    [Description("Categoria 11")]
    Categoria11       
}

@Edit 2

Creation of dropdownlist:

@Html.DropDownList("ddlCategoriaDiurna", 
           (ViewBag.CategoriaDiurna as SelectList), 
            string.Empty)                   
  • Como sabem, não da pra usar ToString I don’t know about that, can you explain what the problem is? Actually tell me where the problem is, what’s going on, what should happen, what you’re talking about.

  • So, Tostring or any conversion to string does not work inside Lynne, because there is something similar in the database. The problem occurs on the line that compares Categoriadiurna to the one selected in the dropdownlist that comes from the screen. In the case o.Categoriadiurna is an Enum, and ddlCategoriaDiurna is a string, I would like to know how to compare this inside the lambda.

  • Is using in database, already helps explain. The Enum also does not exist.

3 answers

2

The value of this ddlCategoriaDiurna comes from Category 1, as an example?

If so, you could read the value Description of your enum

public static string Descricao(this System.Enum itemEnum)
{
   DescriptionAttribute descricao = (DescriptionAttribute)itemEnum.GetType()
        .GetField(itemEnum.ToString())
          .GetCustomAttributes(typeof(DescriptionAttribute), false)
        .FirstOrDefault();
   string retorno = itemEnum.ToString();
   if (descricao != null)
       retorno = descricao.Description;
   return retorno;
}

In a enum

public enum Carro
{
    [Description("Carro Mercedes")]
    Mercedes,
    [Description("Carro Ferrari")]
    Ferrari,
    [Description("Carro Jaguar")]
    Jaguar,
    Porche
}

An example of use with lambda

Carro[] carros = new []{ Carro.Ferrari, Carro.Jaguar };
string texto = Carro.Ferrari.Descricao();
// texto = "Carro Ferrari"
if (carros.Any(c => c.Descricao() == texto))
    Console.WriteLine("Correto");
else
    Console.WriteLine("Incorreto");

// Resultado: Correto
  • Yes, it would come categoria1, as you mentioned, however my problem, is when the user chooses the Null option.

  • I put in the second edition now, as I create the dropdownlist, in case I leave the first option as string.Empty, in case the user does not want to use this filter.

  • In your example you could put in the location of the.Categoriadiurna == ddlCategoriaDiurna. For (ddlCategoriaDiurna == string.Empty || o.Categoriadiurna == ddlCategoriaDiurna)

1


I was able to solve it this way :

I created a method to find the string passed on screen on my Enum, if it was null, return to categorie1 by default :

public CategorizacaoRamaisEnum retornarEnum(string ddlSelecionado) 
{
     return string.IsNullOrEmpty(ddlSelecionado) 
             ? CategorizacaoRamaisEnum.Categoria1 
             :(CategorizacaoRamaisEnum)System.Enum.Parse(typeof(CategorizacaoRamaisEnum),
               ddlSelecionado);
}

I validated the return and if the past value existed in enum:

CategorizacaoRamaisEnum retornoCategoriaDiurna = retornarEnum(ddlCategoriaDiurna);
bool result = Enum.GetNames(typeof(CategorizacaoRamaisEnum)).Contains(ddlCategoriaDiurna);

And finally in mine query Linq:

listaItensSolicitados = os.Site == null ?      this.itemSolicitadoService.Consultar(o =>
            o.ItemServico.Servico.Chave == 9 &&
            o.ChaveOrgao == os.Orgao.Chave
            && o.Numero.Contains(ramal)
            && o.Instalado == true          
            && (result ? o.CategoriaDiurna == retornoCategoriaDiurna : o.Instalado == true)
            && (o.Depreciado == null
            || o.Depreciado == false)).Take(200).ToList()

I know it got redundant in the fake ternary, but that way it solved my problem. If anyone thinks of a more elegant way, kindly put it there, that will help me improve.

0

From what I understand the problem is that you have an "Enum" with strings.

Point 1: If you do not explicitly state the value of that enum it assumes the launch order and infers numbers

Example:

enum Meses:short
{
    Janeiro,
    Fevereiro,
    ...
}

In this case the values would be 0, 1 and so on.

The best solution I can give you is to map this enum to a dictionary or to create a class enum with the strings you want to compare. Another solution would be to create an auxiliary table in the database to have these values registered there, in case they can be changed or added and not leave this enum hard coded.

  • I already have Enum mapped to an auxiliary table in the bank.

Browser other questions tagged

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