在 C# 中把列表新增到另一個列表

Muhammad Maisam Abbas 2024年2月16日
在 C# 中把列表新增到另一個列表

本教程將討論在 C# 中將一個列表的元素新增到另一列表的末尾的方法。

使用 C# 中的 List.AddRange() 函式將列表新增到另一個列表

在一個列表的末尾附加一個列表元素的最簡單方法是在 C# 中使用 List.AddRange() 方法。List.AddRange(x) 方法在列表中新增集合 x 的元素。以下程式碼示例向我們展示瞭如何使用 C# 中的 List.AddRange() 函式將一個列表新增到另一個列表。

using System;
using System.Collections.Generic;

namespace add_list {
 class Program {
   static void Main(string[] args) {
     List<string> first = new List<string> { "do", "rey", "me" };
     List<string> second = new List<string> { "fa", "so", "la", "te" };
     first.AddRange(second);
     foreach (var e in first) {
       Console.WriteLine(e);
     }
   }
 }
}

輸出:

do
rey
me
fa
so
la
te

在上面的程式碼中,我們建立並初始化了 2 個字串列表,分別是 firstsecond。我們在 first 列表的末尾附加了 second 列表元素,並新增了 first.AddRange(second) 函式。最後,我們顯示了 first 列表中的元素。

Muhammad Maisam Abbas avatar Muhammad Maisam Abbas avatar

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

LinkedIn

相關文章 - Csharp List