Optimize foreach

11

I need to check if listaContrato items exist in listaPendencia , if there is no enable to false to be disabled on the screen.

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

If there are solutions that are not foreach , they 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;
        }
    }
}
    
asked by anonymous 10.11.2016 / 15:18

2 answers

8

I have no way to test, but try the following LINQ (but I doubt it is faster than a for).

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;
}
    
10.11.2016 / 17:48
4

Apparently just to improve breaking the loop once you find what you expect. Without seeing a larger context, you can not improve it any 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;
        }
    }
}
    
10.11.2016 / 15:29