Is it possible to evaluate a ternary expression with 3 possible values?

Asked

Viewed 1,752 times

3

Let’s say I have this account:

var total = valor1 / valor2;

The result could be three possible values, like:

  • total > 5
  • total > 0 and total < 5
  • a positive value

Note: They are percentage values, therefore 5% is equal to 0.05.

Could use a if that tested everything, but the question is: similar to a ternary operator, it is possible?

  • Actually I need to paint a Boxview depending on the result. I tried this but I can’t put boxview to paint.

  • 2

    Any solution proposed will have to follow one of the 3 possible paths. And that I know has no way to do in a simplified way. Most likely it encapsulates itself in a method.

2 answers

10


No. The ternary operator only works with two expressions.

The most you can do is something similar to the code below, nesting the ternaries.

Keep in mind that this makes code extremely difficult to read.

var resultado = total < 5 ? 
                  ((total > 0) ? "Menor que cinco, mas maior que zero" 
                               : "Menor que cinco, zero ou menos") 
                : "Maior ou igual a cinco";

See working on . NET Fiddle


Editing

As I know that you are an admirer of expressions, Lambdas, functions and etc. And I also remember a question that you deleted where you asked something like avoid a lot of if’s using expressions, I decided to write a code with this adapted to the current problem.

Keep in mind that this is not a concrete solution given the circumstances, you can rather take advantage of this code, but I believe not for the current problem.

Explanation: The code is basically based on a list of key-value pairs, where each element of this list has as its key an expression that takes as input (parameter) a decimal number and returns a boolean (Func<decimal, bool>). The values of these pairs are one string descriptive with the result, obviously this can be switched to anything, but I decided to leave so to get more illustrative.

The method ValidarTotal iterates over all these items, calls the function (which is the key of the pair) passing the parameter valor as a function input and, if the result is true, returns the value of the pair. Obviously it is possible to change so that it is grouped, I did this in the method ValidarTotalAgrupado. His idea is the same as the first, with the difference that will return a string with all values where the function returned true and that I used LINQ.

Code:

KeyValuePair<Func<decimal, bool>, string>[] pares = new[]   
{
    new KeyValuePair<Func<decimal, bool>, string>(valor => valor > 5, "Maior que 5"),
    new KeyValuePair<Func<decimal, bool>, string>(valor => valor > 0 && valor < 5, "Maior que 0 e menor que 5"),
    new KeyValuePair<Func<decimal, bool>, string>(valor => valor > 0, "Número positivo")
};

static string ValidarTotalAgrupado(decimal valor, params KeyValuePair<Func<decimal, bool>, string>[] pares)
{
    var ret = pares.Where(p => p.Key(valor))
                   .Select(p => p.Value)
                   .Aggregate((a, b) => $"{a}, {b}");

    return ret;
}

static string ValidarTotal(decimal valor, params KeyValuePair<Func<decimal, bool>, string>[] pares)
{
    foreach(var item in pares)
    {
        if(item.Key(valor)) {
            return item.Value;
        }
    }   
    return null;
}

void Main()
{   
    var testes = new[] 
    {
        new { Valor = 6m },
        new { Valor = 2m },
        new { Valor = 0.5m }
    };

    foreach(var teste in testes)
    {
        var res = ValidarTotal(teste.Valor, pares);
        var resAgrupado = ValidarTotalAgrupado(teste.Valor, pares);

        Console.WriteLine($"Valor: {teste.Valor:n2}\nResultado: {res}\nAgrupado: {resAgrupado}\n");
    }
}

See working on . NET Fiddle.

  • 1

    Yes, as said falls in the same if, maybe the if is cleaner to parallel.

  • @I made an edition that I think you will find cool.

  • Linq, I didn’t test here with me because I had to focus on finishing an app layout that I’m developing, but I’m going to test it. I will mark the answer, because in Fiddle worked and I think it will work with me. Any coi, we go back and post, but I think it does solve. I deleted that post, because it was not making sense the form of the question and would receive down and as there was no answer I deleted. Yes, I’m a licker and I hate IF’s, rs.

  • @pnet Quiet, do not forget to read the body of the answer, have important considerations

10

It is possible to use nested conditional operators, but is discouraged by decreasing readability, although it can help a little:

resultado = total > 5 ? 5 :
            total < 5 ? 1 :
            total > 0 ? 0;

I put in the Github for future reference.

  • Falls in the same way IF, since the aim is to improve readability.

Browser other questions tagged

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