如何將第二個列表追加到 C# 中的現有列表中?


使用 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);
      }
   }
}

更新於: 2023-10-04

32K+ 瀏覽

啟動你的 職業生涯

完成該課程以取得認證

開始
廣告
© . All rights reserved.