C# 合并两个List对象的方法

在 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> 的方法。你可以根据具体需求选择最适合的方式。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值