Home > Backend Development > C#.Net Tutorial > How to copy a collection to an array using C#?

How to copy a collection to an array using C#?

WBOY
Release: 2023-08-25 15:53:05
forward
1623 people have browsed it

How to copy a collection to an array using C#?

Copy the collection into an array, first set it to −

List < string > list1 = new List < string > ();
list1.Add("Car");
list1.Add("Bus");
list1.Add("Motorbike");
list1.Add("Train");
Copy after login

Now declare an array of strings and copy −

using the CopyTo() method
string[] arr = new string[20];
list1.CopyTo(arr);
Copy after login

Let’s take a look at the complete code to copy a collection to an array −

Example

using System;
using System.Collections.Generic;
using System.Linq;

public class Demo {
   public static void Main() {
      List < string > list1 = new List < string > ();
      list1.Add("Car");
      list1.Add("Bus");
      list1.Add("Motobike");
      list1.Add("Train");

      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);
      }
   }
}
Copy after login

The above is the detailed content of How to copy a collection to an array using C#?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template