C# 合并多个 List 集合 - 使用 Concat 方法

在 C# 编程中,经常需要将多个 List 集合合并成一个。LINQ 提供了 Concat 方法,能够方便高效地完成这项任务。

示例代码:

List<int> list1 = new List<int>() { 1, 2, 3 };
List<int> list2 = new List<int>() { 4, 5, 6 };
List<int> list3 = new List<int>() { 7, 8, 9 };

// 使用 Concat 方法合并 List
List<int> mergedList = list1.Concat(list2).Concat(list3).ToList();

// mergedList 现在包含所有元素: { 1, 2, 3, 4, 5, 6, 7, 8, 9 }

解释:

  1. 我们首先创建了三个 List<int> 类型的集合:list1list2list3
  2. 使用 list1.Concat(list2)list1list2 合并,然后再次使用 Concat(list3)list3 合并到结果中。
  3. 最后,我们使用 ToList() 方法将合并后的结果转换为新的 List<int> 对象,并赋值给 mergedList

通过这种方式,mergedList 变量现在包含了所有三个原始 List 中的元素。

总结:

使用 LINQ 的 Concat 方法可以简单高效地合并多个 List 集合。此方法适用于所有类型的 List,例如 List<int>List<string> 等。

C# 合并多个 List 集合 - 使用 Concat 方法高效合并

原文地址: https://www.cveoy.top/t/topic/f2nB 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录