using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// 创建两个列表
List<int> list1 = new List<int> { 1, 2, 3 };
List<int> list2 = new List<int> { 4, 5, 6 };
// 方法一:使用 AddRange 方法合并列表
List<int> mergedList1 = new List<int>(list1);
mergedList1.AddRange(list2);
Console.WriteLine("使用 AddRange 方法合并后的列表: " + string.Join(", ", mergedList1));
// 方法二:使用 Concat 方法合并列表(返回 IEnumerable<T>)
IEnumerable<int> mergedList2 = list1.Concat(list2);
Console.WriteLine("使用 Concat 方法合并后的列表: " + string.Join(", ", mergedList2));
// 方法三:使用 LINQ 的 Concat 方法并转换为 List
List<int> mergedList3 = list1.Concat(list2).ToList();
Console.WriteLine("使用 LINQ Concat 方法并转换为 List 后的列表: " + string.Join(", ", mergedList3));
}
}
AddRange 方法:AddRange
是 List<T>
类的一个方法,它将另一个集合中的所有元素添加到当前列表的末尾。这种方式直接修改了原始列表。
Concat 方法:Concat
是一个扩展方法,返回一个 IEnumerable<T>
,它不会修改原始列表,而是创建一个新的序列,包含两个列表的所有元素。如果你需要将其转换为 List<T>
,可以使用 ToList()
方法。
LINQ Concat 方法:与 Concat
方法类似,但通过 LINQ 查询表达式的方式实现,并且可以直接调用 ToList()
将结果转换为 List<T>
。
以上三种方法都可以实现两个列表的合并,具体选择哪种方式取决于你的需求和代码风格。
上一篇:c#字符串
下一篇:c#匿名函数
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站