How do you convert a list collection into an array in C#?

CsharpProgrammingServer Side Programming

Firstly, set a list collection −

List < string > myList = new List < string > ();
myList.Add("RedHat");
myList.Add("Ubuntu");

Now, use ToArray() to convert the list to an array −

string[] str = myList.ToArray();

The following is the complete code −

Example

 Live Demo

using System;
using System.Collections.Generic;

public class Program {
   public static void Main() {

      List < string > myList = new List < string > ();
      myList.Add("RedHat");
      myList.Add("Ubuntu");

      Console.WriteLine("List...");
      foreach(string value in myList) {
         Console.WriteLine(value);
      }

      Console.WriteLine("Converting to Array...");
      string[] str = myList.ToArray();

      foreach(string s in myList) {
         Console.WriteLine(s);
      }
   }
}

Output

List...
RedHat
Ubuntu
Converting to Array...
RedHat
Ubuntu
raja
Published on 31-Aug-2018 16:51:53
Advertisements