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




C# - JOIN TWO LISTS


How to extend an existing List or join two Lists?


Let us say, we have a List that contains three names, Mohan, Kriti and Salim. And we want to insert a new List with two names Sia and Andrew at the end of the List.


In such case we can use AddRange() method.


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>(){"Sia", "Andrew"};
        
        x.AddRange(y);
        
        foreach (var data in x)  
        {  
            System.Console.WriteLine(data);  
        }
    }    
}


Output :



  Mohan
  Kriti
  Salim
  Sia
  Andrew

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

Also we have another List that contains, Sia and Andrew.


	var y = new List<string>(){"Sia", "Andrew"};
C_Sharp


Next, we have used the AddRange() function to add the new List y that contains Sia and Andrew at the end of the List x.


x.AddRange(y)

And the List y is joined with x.

C_Sharp

Output :



  Mohan
  Kriti
  Salim
  Sia
  Andrew