在 C# 中合并两个 List<T>
对象是非常简单的,有多种方法可以实现这一目标。以下是几种常见的做法:
1. 使用 AddRange
方法
这是最直接的方法之一,你可以直接调用一个列表的 AddRange
方法来添加另一个列表中的所有元素。
csharp
深色版本
1List<int> list1 = new List<int> { 1, 2, 3 };
2List<int> list2 = new List<int> { 4, 5, 6 };
3
4list1.AddRange(list2);
5
6// 现在 list1 包含 { 1, 2, 3, 4, 5, 6 }
2. 使用 LINQ
如果你喜欢 LINQ(Language Integrated Query),你可以使用 Concat
方法来合并两个列表,然后再转换回 List<T>
。
csharp
深色版本
1List<int> list1 = new List<int> { 1, 2, 3 };
2List<int> list2 = new List<int> { 4, 5, 6 };
3
4var combinedList = list1.Concat(list2).ToList();
5
6// 现在 combinedList 包含 { 1, 2, 3, 4, 5, 6 }
3. 使用集合操作符
如果你使用的是 C# 5.0 及以上版本,可以使用集合操作符 Union
来合并两个列表,这会自动去重(如果元素实现了 IEquatable<T>
接口)。
csharp
深色版本
1List<int> list1 = new List<int> { 1, 2, 3 };
2List<int> list2 = new List<int> { 3, 4, 5 };
3
4var combinedList = list1.Union(list2).ToList(); // 去重后的结果为 { 1, 2, 3, 4, 5 }
5
6// 如果不需要去重,可以直接使用 Concat
7var combinedListNoDuplicateRemoval = list1.Concat(list2).ToList(); // 结果为 { 1, 2, 3, 3, 4, 5 }
4. 使用 ForEach
或 For
循环
虽然这种方法不如前面的方法简洁,但它提供了更多的灵活性,尤其是在需要执行额外操作的时候。
csharp
深色版本
1List<int> list1 = new List<int> { 1, 2, 3 };
2List<int> list2 = new List<int> { 4, 5, 6 };
3
4foreach (int item in list2)
5{
6 list1.Add(item);
7}
8
9// 现在 list1 包含 { 1, 2, 3, 4, 5, 6 }
5. 使用 List<T>.AddAll
扩展方法
如果你经常需要合并多个列表,可以考虑定义一个扩展方法来简化这个过程:
csharp
深色版本
1public static class ListExtensions
2{
3 public static void AddAll<T>(this List<T> source, IEnumerable<T> items)
4 {
5 foreach (T item in items)
6 {
7 source.Add(item);
8 }
9 }
10}
11
12// 使用示例
13List<int> list1 = new List<int> { 1, 2, 3 };
14List<int> list2 = new List<int> { 4, 5, 6 };
15
16list1.AddAll(list2); // 现在 list1 包含 { 1, 2, 3, 4, 5, 6 }
以上就是一些常用的合并两个 List<T>
的方法。你可以根据具体需求选择最适合的方式。