How to join or concatenate two lists in C#?

CsharpProgrammingServer Side Programming

To concatenate two lists, use AddRange() method.

Set the first list −

var products1 = new List < string > ();
products1.Add("Belts");
products1.Add("Tshirt");
products1.Add("Trousers");

Set the second list −

var products2 = new List < string > ();
products2.Add("Footwear");
products2.Add("Electronics");

To concatenate both the lists −

products1.AddRange(products2);

The following is the complete code −

Example

 Live Demo

using System.Collections.Generic;
using System;

namespace Demo {
   public static class Program {
      public static void Main() {
         var products1 = new List < string > ();
         products1.Add("Belts");
         products1.Add("Tshirt");
         products1.Add("Trousers");

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

         var products2 = new List < string > ();
         products2.Add("Footwear");
         products2.Add("Electronics");

         Console.WriteLine("Our list2....");
         foreach(var p in products2) {
            Console.WriteLine(p);
         }
         products1.AddRange(products2);
         Console.WriteLine("Concatenated list....");
         foreach(var p in products1) {
            Console.WriteLine(p);
         }
      }
   }
}

Output

Our list1....
Belts
Tshirt
Trousers
Our list2....
Footwear
Electronics
Concatenated list....
Belts
Tshirt
Trousers
Footwear
Electronics
raja
Published on 31-Aug-2018 08:19:23
Advertisements