c# – If/else repetition how to reduce and improve code?

Question:

I'm starting with programming and a question arose during my conditions. I check how many times the result was true, and how many times it was false. Problem is, it's not giving me the actual result.

The only way I found it to work is as follows:

if (Lstr_Resultado1 == "Verdadeiro")
{
    Lint_TotalVerdadeiro++;
}
else
{
    Lint_TotalFalso++;
}
if (Lstr_Resultado2 == "Verdadeiro")
{
    Lint_TotalVerdadeiro++;
}
else
{
    Lint_TotalFalso++;
}
if (Lstr_Resultado3 == "Verdadeiro")
{
    Lint_TotalVerdadeiro++;
}
else
{
    Lint_TotalFalso++;
}

I believe there is a more performative way to do this. I know I'm starting and the application is simple but I try to reduce the use of machine processing. What would be the best way to solve this amount of if / else?

Answer:

You can add your results to a lista of your result type (string, int, etc…), then do a foreach to go through your list checking if the field is true or not:

var resultados = new List<String>();

resultados.Add(Lstr_Resultado1);

foreach (var resultado in resultados)
{
  if(resultado == "Verdadeiro")
    Lint_TotalVerdadeiro++;
  else
    Lint_TotalFalso++;
}
Scroll to Top