如何复制或克隆 C# 列表?


要复制或克隆一个 C# 列表,首先设置列表 −

List < string > list1 = new List < string > ();
list1.Add("One");
list1.Add("Two");
list1.Add("Three");
list1.Add("Four");

现在声明一个字符串数组并使用 CopyTo() 方法来复制。

string[] arr = new string[20];
list1.CopyTo(arr);

让我们看看将列表复制到一维数组的完整代码。

示例

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");
      list1.Add("Three");
      list1.Add("Four");

      Console.WriteLine("First list...");
      foreach(string value in list1) {
         Console.WriteLine(value);
      }

      string[] arr = new string[20];
      list1.CopyTo(arr);

      Console.WriteLine("After copy...");

      foreach(string value in arr) {
         Console.WriteLine(value);
      }
   }
}

更新于:2020 年 6 月 21 日

3 千次浏览

启动你的 职业生涯

通过完成课程获得认证

开始吧
广告
© . All rights reserved.