Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




C# - REPLACE LIST ELEMENTS


Change/Replace an Item in a List using index


Let us say, we have a List that contains three names, Mohan, Kriti and Salim. And we want to replace the name Kriti with a new name Paul.


Example :



using System.Collections.Generic;
    
public class MyApplication
{
    public static void Main(string[] args)
    {
        var x = new List<string>(){"Mohan", "Kriti", "Salim"};
        x[1] = "Paul";
        foreach (var data in x)  
        {  
            System.Console.WriteLine(data);  
        }
    }    
}


Output :



  Mohan
  Paul
  Salim

So, in the above code we have created a List x.


var x = new List<string>(){"Mohan", "Kriti", "Salim"};

Now, let us see, how the values are positioned in the List

C_Sharp

Now, if we see the above diagram, Kriti resides at position/index 1. So, what we do is, just replace the position/index 1 (i.e. x[1]) with the new name Paul.


x[1] = "Paul"
C_Sharp


And we get the below output,

Output :



  Mohan
  Paul
  Salim