Join two or more lists in C#
This post will discuss how to join two or more lists in C#.
1. Using Enumerable.Concat method
An elegant way to combine multiple lists together is using LINQ’s Concat() method. For example, the following code concatenate elements of the three lists in the original order.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { List<int> a = new List<int>() { 1, 2, 3 }; List<int> b = new List<int>() { 4, 5 }; List<int> c = new List<int>() { 6, 7, 8 }; var result = a.Concat(b).Concat(c).ToList(); Console.WriteLine(String.Join(", ", result)); // 1, 2, 3, 4, 5, 6, 7, 8 } } |
2. Using List.AddRange method
An alternative way of concatenating multiple lists is to construct a new list and then apply the List.AddRange() method, passing each list to it. The following example demonstrates this usage.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<int> a = new List<int>() { 1, 2, 3 }; List<int> b = new List<int>() { 4, 5 }; List<int> c = new List<int>() { 6, 7, 8 }; var result = new List<int>(a.Count + b.Count + c.Count); result.AddRange(a); result.AddRange(b); result.AddRange(c); Console.WriteLine(String.Join(", ", result)); // 1, 2, 3, 4, 5, 6, 7, 8 } } |
3. Using List.Aggregate method
Finally, we can use the Enumerable.Aggregate method to combine multiple lists into a single list. The Aggregate() method applies an accumulator function on each element of a sequence. It is available in LINQ and can be used as follows:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static List<T> Concat<T>(params List<T>[] lists) { return lists.Aggregate(new List<T>(), (x, y) => x.Concat(y).ToList());; } public static void Main() { List<int> a = new List<int>() { 1, 2, 3 }; List<int> b = new List<int>() { 4, 5 }; List<int> c = new List<int>() { 6, 7, 8 }; var result = Concat(a, b, c); Console.WriteLine(String.Join(", ", result)); // 1, 2, 3, 4, 5, 6, 7, 8 } } |
That’s all about joining two or more lists in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)