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




C# - COPY FROM LIST


How to copy one List to the other?


Example :



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


Output :



  Mohan
  Kriti
  Salim

So, in the above code we have created a List and initialised to the variable x.


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

Below is how the values are positioned in the List,

C_Sharp

Then we have created a new List and and passed the List x as parameter.


var y = new List<string>(x);

And the new List y gets all the values of the List x.

C_Sharp

And we get the below output,

Output :



  Mohan
  Kriti
  Salim

Note : Do not use the '=' operator to copy a List to the other(i.e. If there are two Lists 'x' and 'y'. Do not use y = x). Because in that case any changes made to the List 'x' will be reflected in the copied List 'y'.