How to simplify a foreach by a Linq - Lambda expression

3

Performance is not a problem in my project, I want to know a simpler and readable replacement for my foreach using Linq and Lambda (if possible).

// 'DiscoVirtual' é uma classe
// 'this.HDs' é um 'List<DiscoVirtual>'
// 'Atual' e 'Novo' são instâncias de 'DiscoVirtual'

foreach (DiscoVirtual d in this.HDs)
{
    if (d == Atual)
    {
        this.HDs.Remove(Atual);
        if (Novo != null) this.HDs.Add(Novo);
    }
}

In addition to this, if Novo is null I only want it to remove Atual (I've completed the code).

    
asked by anonymous 23.08.2015 / 19:27

1 answer

5

This code can not be converted directly to LINQ because it has imperative style and is not functional.

In other words, LINQ promotes a functional style (no side effects, referential transparency, and with immutable data), and this code violates all 3 of these rules by changing the status of the list with Add and Remove .

/ p>

To use a functional style, we must, from the current list of HDs , compute a new list, leaving the original intact.

Then we replace the HDs list with the new list.

HDs = HDs.Select(hd => hd == Actual? Novo : hd).ToList();
    
23.08.2015 / 20:30