Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

คุณจะแปลงคอลเล็กชันรายการเป็นอาร์เรย์ใน C # ได้อย่างไร


ขั้นแรก ตั้งค่าการรวบรวมรายการ -

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

ตอนนี้ ใช้ ToArray() เพื่อแปลงรายการเป็นอาร์เรย์ -

string[] str = myList.ToArray();

ต่อไปนี้เป็นรหัสที่สมบูรณ์ -

ตัวอย่าง

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);
      }
   }
}

ผลลัพธ์

List...
RedHat
Ubuntu
Converting to Array...
RedHat
Ubuntu