-2

I have a list

   List < double > newlist = new List<double>{5.0,1.1,2.1,5.1,0.2,5.2,7.5}

using System.Linq how to change all values between 5<i<6 to 5.5?

Wiley Ng
  • 307
  • 3
  • 14
  • 1
    Mutating an existing list is not something you'd use Linq for - just use a `for` loop. – Matthew Watson Jan 21 '22 at 12:06
  • Thanks! @MatthewWatson I see. I was simply looking for one-line version of what I want to do. As others have pointed out, LINQ is for querying data, it is not for doing updates. – Wiley Ng Jan 21 '22 at 12:13

1 Answers1

0

approach with linq - that replaces the existing List<double> with a new one

//[5.0,1.1,2.1,5.5,0.2,5.5,7.5]
newlist = newlist.Select(x => x > 5 && x < 6 ? 5.5d : x).ToList(); 

approach with a for loop - that one only changes the affected values

for (int i = 0; i < newlist.Count; i++)
{
    if (newlist[i] > 5 && newlist[i] < 6)
    {
        newlist[i] = 5.5d;
    }
}
fubo
  • 44,811
  • 17
  • 103
  • 137
  • That's fine if the OP wants to create a new list, but it's not actually changing the numbers IN a list (the question seems to be asking to mutate an existing list). – Matthew Watson Jan 21 '22 at 12:10
  • @MatthewWatson good point - I've added a classy for-loop – fubo Jan 21 '22 at 12:14