Francisco Q.
Francisco Q.

Reputation: 177

RemoveAll inside foreach with linq

I can see why this is allowed:

foreach (var paralelos in ParalelosSeleccionadosTemp)
{
    foreach (var horario in paralelos.Horarios)
    {
        for (int i = 0; i < horario.DetallesHorario.Count; i++)
        {
            if (feriados.Contains(horario.DetallesHorario[i].Fecha.Value))
            {
                horario.DetallesHorario.RemoveAt(i);
                i--;
            }
        }
    }
}

but how about this?

ParalelosSeleccionadosTemp
    .ForEach(p => p.Horarios.ToList()
        .ForEach(q => q.DetallesHorario.ToList()
            .RemoveAll(x => feriados.Contains(x.Fecha.Value))));

I don't understand why this fails and doesn't remove any item.

Upvotes: 1

Views: 584

Answers (2)

BartoszKP
BartoszKP

Reputation: 35891

ToList() creates a copy of the collection. Thus the original remains unaffected.

All you need to do for the second snippet to work is to remove the unnecessary call to ToList():

ParalelosSeleccionadosTemp
    .ForEach(p => p.Horarios.ToList()
        .ForEach(q => q.DetallesHorario
            .RemoveAll(x => feriados.Contains(x.Fecha.Value))));

That of course will work only if DetallesHorario is of type List<T>. Otherwise you need to tweak this to use appropriate method (or create one) to remove elements from this collection.

Note that also if Horarios is a List<T> then the first call to ToList() is also obsolete.

Upvotes: 7

Yosi Dahari
Yosi Dahari

Reputation: 6999

The .ToList() creates a new list and modify it and therefor your list isn't updated.

The way to do it is the first option, or removing the .ToList()

Upvotes: 0

Related Questions