如何在 C# 中将第二个列表附加到现有列表?
csharpprogrammingserver side programming更新于 2025/5/28 9:07:17
使用 AddRange() 方法将第二个列表附加到现有列表。
这是列表一 −
List < string > list1 = new List < string > ();
list1.Add("One");
list1.Add("Two");
这是列表二 −
List < string > list2 = new List < string > ();
list2.Add("Three");
ist2.Add("Four");
现在让我们添加 −
list1.AddRange(list2);
让我们看看完整的代码。
示例
using System;
using System.Collections.Generic;
using System.Linq;
public class Demo {
public static void Main() {
List < string > list1 = new List < string > ();
list1.Add("One");
list1.Add("Two");
Console.WriteLine("First list...");
foreach(string value in list1) {
Console.WriteLine(value);
}
Console.WriteLine("Second list...");
List < string > list2 = new List < string > ();
list2.Add("Three");
list2.Add("Four");
foreach(string value in list2) {
Console.WriteLine(value);
}
Console.WriteLine("After Append...");
list1.AddRange(list2);
foreach(string value in list1) {
Console.WriteLine(value);
}
}
}

