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



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
Updated on: 2020-06-22T13:05:09+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements