How to simplify a foreach by a Linq expression - Lambda

Asked

Viewed 965 times

3

Performance is not an issue 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);
    }
}

Beyond the but, if Novo for null I just want it removed Atual (I supplemented the code).

  • The estate HDs has Setter or just getter?

  • To clarify, the intention of the code is to replace the disk Actual for Novo? And if the list doesn’t contain Actual, nothing happens?

  • Both: { get; private set; }. This section is within the class.

  • Atual is already on the list this.HDs. Can’t not be. I want to change the reference of Atual by reference to Novo

1 answer

5


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

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

To employ a functional style, we must, from the current list of HDs, calculate 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();

Browser other questions tagged

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