如何连接或合并 C# 中的两个列表?
要连接两个列表,请使用 AddRange() 方法。
设置第一个列表 -
var products1 = new List < string > (); products1.Add("Belts"); products1.Add("Tshirt"); products1.Add("Trousers");
设置第二个列表 -
var products2 = new List < string > (); products2.Add("Footwear"); products2.Add("Electronics");
连接两个列表 -
products1.AddRange(products2);
以下是完整代码 -
示例
using System.Collections.Generic; using System; namespace Demo { public static class Program { public static void Main() { var products1 = new List < string > (); products1.Add("Belts"); products1.Add("Tshirt"); products1.Add("Trousers"); Console.WriteLine("Our list1...."); foreach(var p in products1) { Console.WriteLine(p); } var products2 = new List < string > (); products2.Add("Footwear"); products2.Add("Electronics"); Console.WriteLine("Our list2...."); foreach(var p in products2) { Console.WriteLine(p); } products1.AddRange(products2); Console.WriteLine("Concatenated list...."); foreach(var p in products1) { Console.WriteLine(p); } } } }
输出
Our list1.... Belts Tshirt Trousers Our list2.... Footwear Electronics Concatenated list.... Belts Tshirt Trousers Footwear Electronics
广告