How to append a second list to an existing list in C#?


Use the AddRange() method to append a second list to an existing list.

Here is list one −

List < string > list1 = new List < string > ();

list1.Add("One");
list1.Add("Two");

Here is list two −

List < string > list2 = new List < string > ();

list2.Add("Three");
ist2.Add("Four");

Now let us append −

list1.AddRange(list2);

Let us see the complete code.

Example

using System;
using System.Collections.Generic;
using System.Linq;

public class Demo {
   public static void Main() {

      List < string > list1 = new List < string > ();
      list1.Add("One");
      list1.Add("Two");
      Console.WriteLine("First list...");
      foreach(string value in list1) {
         Console.WriteLine(value);
      }

      Console.WriteLine("Second list...");
      List < string > list2 = new List < string > ();

      list2.Add("Three");
      list2.Add("Four");
      foreach(string value in list2) {
         Console.WriteLine(value);
      }

      Console.WriteLine("After Append...");
      list1.AddRange(list2);
      foreach(string value in list1) {
         Console.WriteLine(value);
      }
   }
}

Updated on: 04-Oct-2023

25K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements