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

CsharpProgrammingServer Side Programming

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);
      }
   }
}
raja
Published on 14-Aug-2018 07:37:45
Advertisements