Optimize foreach

Asked

Viewed 359 times

11

I need to check the items from listaContrato exist in the listaPendencia, if I don’t exist enable to false to be disabled on screen.

What can I do to improve the performance of foreach below? Both lists are List<>.

If there are solutions that are not foreach are also welcome.

foreach (System.Windows.Controls.CheckBox item in pendenciaController.ListaCliente)
{
    item.IsEnabled = false;

    foreach (Pendencia pendencia in pendenciaController.ListaPendencia)
    {
        if (pendencia.ClienteNome.Equals(item.Content))
        {
            item.IsEnabled = true;
            break;
        }
    }
}
  • Denis, welcome to Sopt. You are in the Portuguese-speaking community, please translate your question. I recommend that you make a Tour by the community.

  • 1

    Grande @Denis aqui é o Stackoverflow Brasil, idioma Português do Brasil, por favor fazer as devida traduções...

  • Done! Now please withdraw the negative vote =)

  • 1

    No obligation to say, but the vote wasn’t my @Denis just to be clear.

  • I know it wasn’t...

  • You could improve the context, is obliged to make these two foreach?

  • I edited Virgilio.

  • @Marcelodeandrade I believe you have negative, I still deserve the negative?

  • @Denis already removed, you no longer have negatives in question :D

  • Grateful! hehe

Show 5 more comments

2 answers

8


I have no way to test, but try the following LINQ (but I doubt it will be faster than one).

var lista = 
    from checkBox in pendenciaController.ListaCliente
    join pendencia in pendenciaController.ListaPendencia on checkBox.Content equals pendencia.ClienteNome into pendencias
    from pendencia in pendencias.DefaultIfEmpty()
    select new { CheckBox = checkBox, Pendencia = pendencia };

foreach (var item in lista)
{
    item.CheckBox.IsEnabled = item.Pendencia != null;
}
  • its witchcraft rs made the time fall too much! A 9-second fell to less than 1!!! You WIN!!!

4

Apparently only to improve by breaking the loop once you find what you expect. Without seeing a larger context you can’t improve more.

You can write this in the most idiomatic way for C, you can avoid this flag:

foreach (var item in pendenciaController.ListaContrato) {
    foreach (var pendencia in pendenciaController.ListaPendencia) {
        if (pendencia.Contrato.Equals(item.Content)) {
            item.IsEnabled = false;
            break;
        }
    }
}

I put in the Github for future reference.

  • with the break improved 40% one of the foreach fell from 9 to 5 seconds.

  • If you don’t find another solution I will mark yours as a response.

Browser other questions tagged

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