Sử dụng phương thức AddRange () để thêm danh sách thứ hai vào danh sách hiện có.
Đây là danh sách một -
List < string > list1 = new List < string > ();
list1.Add("One");
list1.Add("Two"); Đây là danh sách hai -
List < string > list2 = new List < string > ();
list2.Add("Three");
ist2.Add("Four"); Bây giờ, hãy để chúng tôi thêm vào -
list1.AddRange(list2);
Hãy cho chúng tôi xem mã hoàn chỉnh.
Ví dụ
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);
}
}
}