Join two lists in C#
This post will discuss how to join two lists in C#. The solution should contain all elements of the first list, followed by all elements of the second list.
1. Using Enumerable.Concat() method
The Enumerable.Concat() method provides a simple way to join multiple lists in C#. The following example demonstrates the usage of the Concat() method by joining two lists.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
using System; using System.Linq; using System.Collections.Generic; public static class Extension { public static List<T> Join<T>(this List<T> first, List<T> second) { if (first == null) { return second; } if (second == null) { return first; } return first.Concat(second).ToList(); } } public class Example { public static void Main() { List<int> first = new List<int>() { 1, 2, 3, 4, 5 }; List<int> second = new List<int>() { 6, 7, 8, 9 }; List<int> result = first.Join(second); Console.WriteLine(String.Join(",", result)); } } /* Output: 1,2,3,4,5,6,7,8,9 */ |
2. Using AddRange() method
f you need to merge the second list into the first list, use the AddRange() method to add all elements of the second list at the end of the first list. Here’s what the code would look like:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<int> first = new List<int>() { 1, 2, 3, 4, 5 }; List<int> second = new List<int>() { 6, 7, 8, 9 }; first.AddRange(second); Console.WriteLine(String.Join(",", first)); } } /* Output: 1,2,3,4,5,6,7,8,9 */ |
3. Using List<T>.ForEach(Action<T>) method
To merge the second list elements into the first list, we can also use the foreach statement to individually copy each element of the second list to the first list.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<int> first = new List<int>() { 1, 2, 3, 4, 5 }; List<int> second = new List<int>() { 6, 7, 8, 9 }; second.ForEach(item => first.Add(item)); Console.WriteLine(String.Join(",", first)); } } /* Output: 1,2,3,4,5,6,7,8,9 */ |
That’s all about joining two 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 :)