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}

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

相关推荐
uncleTom6666 分钟前
前端布局利器:rem 适配全面解析
前端
谦哥9 分钟前
Claude4免费Vibe Coding!目前比较好的Cursor替代方案
前端·javascript·claude
LEAFF20 分钟前
如何 测试Labview是否返回数据 ?
前端
Spider_Man22 分钟前
🚀 从阻塞到丝滑:React中DeepSeek LLM流式输出的实现秘籍
前端·react.js·llm
心在飞扬23 分钟前
理解JS事件环(Event Loop)
前端·javascript
盏茶作酒2940 分钟前
打造自己的组件库(一)宏函数解析
前端·vue.js
山有木兮木有枝_1 小时前
JavaScript 设计模式--单例模式
前端·javascript·代码规范
一大树1 小时前
Vue3 开发必备:20 个实用技巧
前端·vue.js
颜渊呐1 小时前
uniapp中APPwebview与网页的双向通信
前端·uni-app
10年前端老司机2 小时前
React 受控组件和非受控组件区别和使用场景
前端·javascript·react.js