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.

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 Join[this List first, List second]
{
if [first == null] {
return second;
}
if [second == null] {
return first;
}
return first.Concat[second].ToList[];
}
}
public class Example
{
public static void Main[]
{
List first = new List[] { 1, 2, 3, 4, 5 };
List second = new List[] { 6, 7, 8, 9 };
List result = first.Join[second];
Console.WriteLine[String.Join[",", result]];
}
}
/*
Output: 1,2,3,4,5,6,7,8,9
*/

DownloadRun Code

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. Heres 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 first = new List[] { 1, 2, 3, 4, 5 };
List second = new List[] { 6, 7, 8, 9 };
first.AddRange[second];
Console.WriteLine[String.Join[",", first]];
}
}
/*
Output: 1,2,3,4,5,6,7,8,9
*/

DownloadRun Code

3. Using List.ForEach[Action] 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 first = new List[] { 1, 2, 3, 4, 5 };
List second = new List[] { 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#.

Video liên quan

Chủ Đề