Linq merge two lists
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. Show 1. Using Enumerable.Concat() methodThe 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.
DownloadRun Code 2. Using AddRange() methodf 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. Heres what the code would look like:
DownloadRun Code 3. Using 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 */ |
DownloadRun Code
Thats all about joining two lists in C#.