How to join two lists in C#?

CsharpProgrammingServer Side Programming

To join two lists, use AddRange() method.

Set the first list −

var list1 = new List < string > ();
list1.Add("Keyboard");
list1.Add("Mouse");

Set the second list −

var list2 = new List < string > ();
list2.Add("Hard Disk");
list2.Add("Pen Drive");

To concatenate both the lists −

lists1.AddRange(lists2);

The following is the complete code −

Example

using System.Collections.Generic;
using System;

namespace Demo {
   public static class Program {
      public static void Main() {
         var list1 = new List < string > ();
         list1.Add("Keyboard");
         list1.Add("Mouse");

         Console.WriteLine("Our list1....");
         foreach(var p in list1) {
            Console.WriteLine(p);
         }

         var list2 = new List < string > ();
         list2.Add("Hard Disk");
         list2.Add("Pen Drive");

         Console.WriteLine("Our list2....");
         foreach(var p in list2) {
            Console.WriteLine(p);
         }

         list1.AddRange(list2);

         Console.WriteLine("Concatenated list....");
         foreach(var p in list1) {
            Console.WriteLine(p);
         }
      }
   }
}
raja
Published on 31-Aug-2018 09:08:42
Advertisements