How to update only one element by index in a list of numbers using Linq with C#

1 Answer

0 votes
using System;
using System.Linq;
using System.Collections.Generic;
   
class Program
{
    static void Main() {
        List<int> list = new List<int> { 3, 7, 8, 91, 99, 10, -5, 1, 2 };
        int indexToUpdate = 2;
        int newValue = 8497;

        List<int> updatedList = list
            .Select((value, index) => index == indexToUpdate ? newValue : value)
            .ToList();

        Console.WriteLine(string.Join(", ", updatedList));
    }
}
   
   
   
   
/*
run:
      
3, 7, 8497, 91, 99, 10, -5, 1, 2
    
*/

 



answered Oct 18, 2023 by avibootz
...