How can I improve/simplify my structure?

Asked

Viewed 72 times

-2

We have these various ifs and I wonder if there’s a way to simplify them, make them more objective, easy to understand, ...

Basically, we make a where of retorno to filter that list. In that where, we only add the condition when the variable value is "S".

var retorno = query.Select(x => x.n).Distinct();

if (fin == "S" && ped == "S" && sol == "S")
{
    retorno = retorno.Where(x => x.fin == "S" || x.ped == "S" || x.sol == "S");
}
else if (fin == "S" && ped == "S" && sol == "N")
{
    retorno = retorno.Where(x => x.fin == "S" || x.ped == "S");
}
else if (fin == "S" && ped == "N" && sol == "S")
{
    retorno = retorno.Where(x => x.fin == "S" || x.sol == "S");
}
else if (fin == "S" && ped == "N" && sol == "N")
{
    retorno = retorno.Where(x => x.fin == "S");
}
else if (fin == "N" && ped == "S" && sol == "S")
{
    retorno = retorno.Where(x => x.ped == "S" || x.sol == "S");
}
else if (fin == "N" && ped == "S" && sol == "N")
{
    retorno = retorno.Where(x => x.ped == "S");
}
else if (fin == "N" && ped == "N" && sol == "S")
{
    retorno = retorno.Where(x => x.sol == "S");
}

EDIT (I’m still not satisfied)

var listaRetorno = new List<MeuObjeto>();

if (fin == "S")
{
    listaRetorno = AdicionarItensLista(ret.Where(x => x.fin == "S").ToList(), listaRetorno);
}
if (ped == "S")
{
    listaRetorno = AdicionarItensLista(ret.Where(x => x.ped == "S").ToList(), listaRetorno);
}
if (sol == "S")
{
    listaRetorno = AdicionarItensLista(ret.Where(x => x.sol == "S").ToList(), listaRetorno);
}


private List<MeuObjeto> AdicionarItensLista(List<MeuObjeto> lista, List<MeuObjeto> listaAnterior)
{
    foreach (var item in lista)
    {
            listaAnterior.Add(item);
    }

    return listaAnterior;
}
  • 1

    To use the [tag:revision-code] it is important [Edit] to post and, in addition to providing a functional code for optimization, explain exactly what the code should do.

1 answer

0


Taking the phrase Nesse where, só adicionamos a condição quando o valor da variável for "S". as a premise, one can do something like:

var retorno = query
                .Select(x => x.n)
                .Distinct()
                .Where(x => (fin == "S" && x.fin == fin)
                    || (ped == "S" && x.ped == ped)
                    || (sol == "S" && x.sol == sol));

The logic of this code is that if your filter value is different from "S", it will not be added to Where and all results will be returned. If it is "S", the filter will be added and return only the results with "S".

Browser other questions tagged

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