Dùng AddRange() để nối list2 vào list1 (mutate list1).
var products1 = new List<string> { "Belts", "Tshirt", "Trousers" };
var products2 = new List<string> { "Footwear", "Electronics" };
products1.AddRange(products2);
Ví dụ hoàn chỉnh
using System.Collections.Generic;
using System;
namespace Demo
{
public static class Program
{
public static void Main()
{
var products1 = new List<string> { "Belts", "Tshirt", "Trousers" };
var products2 = new List<string> { "Footwear", "Electronics" };
Console.WriteLine("List1:"); foreach (var p in products1) Console.WriteLine(p);
Console.WriteLine("List2:"); foreach (var p in products2) Console.WriteLine(p);
products1.AddRange(products2);
Console.WriteLine("Nối:"); foreach (var p in products1) Console.WriteLine(p);
}
}
}
Kết quả
List1: Belts Tshirt Trousers List2: Footwear Electronics Nối: Belts Tshirt Trousers Footwear Electronics
So sánh phương pháp nối:
| Phương pháp | Mutate? | Trả về | Distinct? |
|---|---|---|---|
| AddRange | Có | void | Không |
| Concat | Không | IEnumerable | Không |
| Union | Không | IEnumerable | Có |