Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C# program to concat two or more Lists
In C#, you can concatenate multiple List<T> objects using the Concat() method from LINQ. This method creates a new sequence that contains all elements from the original lists in order without modifying the original lists.
Syntax
Following is the syntax for concatenating lists using the Concat() method −
var result = list1.Concat(list2);
For multiple lists, you can chain the Concat() calls −
var result = list1.Concat(list2).Concat(list3);
Using Concat() to Merge Two Lists
Example
using System;
using System.Collections.Generic;
using System.Linq;
public class Demo {
public static void Main() {
var list1 = new List<int>{3, 4};
var list2 = new List<int>{1, 2, 3};
var result = list1.Concat(list2);
Console.WriteLine("Concatenated result:");
foreach(int i in result) {
Console.WriteLine(i);
}
}
}
The output of the above code is −
Concatenated result: 3 4 1 2 3
Using Concat() to Merge Multiple Lists
Example
using System;
using System.Collections.Generic;
using System.Linq;
public class Demo {
public static void Main() {
var list1 = new List<int>{3, 4};
var list2 = new List<int>{1, 2, 3};
var list3 = new List<int>{2, 5, 6};
var result = list1.Concat(list2).Concat(list3);
Console.WriteLine("Result after concatenating three lists:");
foreach(int i in result) {
Console.WriteLine(i);
}
}
}
The output of the above code is −
Result after concatenating three lists: 3 4 1 2 3 2 5 6
Using AddRange() Alternative Method
Another approach to concatenate lists is using the AddRange() method, which modifies the original list −
Example
using System;
using System.Collections.Generic;
public class Demo {
public static void Main() {
var list1 = new List<string>{"Apple", "Banana"};
var list2 = new List<string>{"Orange", "Grape"};
var list3 = new List<string>{"Mango"};
list1.AddRange(list2);
list1.AddRange(list3);
Console.WriteLine("Result using AddRange():");
foreach(string fruit in list1) {
Console.WriteLine(fruit);
}
}
}
The output of the above code is −
Result using AddRange(): Apple Banana Orange Grape Mango
Comparison
| Method | Modifies Original | Return Type | Performance |
|---|---|---|---|
Concat() |
No | IEnumerable<T> | Deferred execution |
AddRange() |
Yes | void | Immediate execution |
Conclusion
The Concat() method is ideal when you want to combine lists without modifying the original collections, while AddRange() is better when you want to merge lists into an existing collection. Both methods preserve the order of elements from the source lists.
