c# list<T> 合并

在C#中,合并List<T>(其中T是任何类型)通常指的是将两个或多个列表合并成一个新的列表。有多种方式可以实现这个目的,下面是一些常见的方法:

方法1:使用AddRange方法 如果你想要将一个列表的所有元素添加到另一个列表的末尾,可以使用AddRange方法。

复制代码
List<int> list1 = new List<int> { 1, 2, 3 };
List<int> list2 = new List<int> { 4, 5, 6 };
 
list1.AddRange(list2); // list1 现在包含 {1, 2, 3, 4, 5, 6}

方法2:使用Concat方法

Concat方法可以创建一个新的列表,其中包含两个列表的所有元素。

复制代码
List<int> list1 = new List<int> { 1, 2, 3 };
List<int> list2 = new List<int> { 4, 5, 6 };
 
var combinedList = list1.Concat(list2).ToList(); // combinedList 现在包含 {1, 2, 3, 4, 5, 6}

方法3:使用LINQ的Union方法

如果你想要合并两个列表,但希望结果中没有重复的元素,可以使用Union方法。

复制代码
List<int> list1 = new List<int> { 1, 2, 3 };
List<int> list2 = new List<int> { 3, 4, 5 };
 
var unionList = list1.Union(list2).ToList(); // unionList 现在包含 {1, 2, 3, 4, 5},去除了重复的3

方法4:使用Add方法循环添加

如果你需要更细粒度的控制,可以手动通过循环将一个列表的元素逐个添加到另一个列表中。

复制代码
List<int> list1 = new List<int> { 1, 2, 3 };
List<int> list2 = new List<int> { 4, 5, 6 };
List<int> combinedList = new List<int>();
 
foreach (var item in list2)
{
    combinedList.Add(item);
}
// 或者更简洁的方式:combinedList.AddRange(list2);

方法5:使用扩展方法自定义合并逻辑

你也可以创建一个自定义的扩展方法来合并列表,根据需要添加特定的逻辑。

复制代码
public static class ListExtensions
{
    public static List<T> Merge<T>(this List<T> first, List<T> second)
    {
        return first.Concat(second).ToList(); // 或者使用其他合并策略
    }
}
 
// 使用方法:
List<int> list1 = new List<int> { 1, 2, 3 };
List<int> list2 = new List<int> { 4, 5, 6 };
List<int> combinedList = list1.Merge(list2); // combinedList 现在包含 {1, 2, 3, 4, 5, 6}

选择哪种方法取决于你的具体需求,比如是否需要处理重复元素,是否需要就地修改其中一个列表等。

相关推荐
IT_陈寒3 小时前
React的useState居然还有这种坑?我差点删库跑路
前端·人工智能·后端
Pedantic4 小时前
SwiftUI 手势笔记
前端·后端
橙子家5 小时前
浏览器缓存之【结构化数据库与缓存】: IndexedDB、Cache storage 和 Storage buckets
前端
user20585561518135 小时前
X6 中边悬浮置顶,规避 `mouseleave` 事件丢失问题
前端
李明卫杭州5 小时前
CSS aspect-ratio 属性完全指南
前端
唐青枫6 小时前
别再乱用 StartNew:C#.NET TaskFactory 任务调度实战详解
c#·.net
Pedantic7 小时前
SwiftUI 手势层级(Gesture Hierarchy)详解
前端
飘尘7 小时前
前端转型全栈(Java后端)的快速上手指引
前端·后端·全栈
一颗烂土豆7 小时前
Meshopt 压缩深度解析,为什么它比 Draco 更快
前端·javascript·webgl