ในการประกาศและเริ่มต้นรายการใน C# ขั้นแรกให้ประกาศรายการ -
List<string> myList = new List<string>()
ตอนนี้เพิ่มองค์ประกอบ -
List<string> myList = new List<string>() {
"one",
"two",
"three",
}; ด้วยเหตุนี้ เราได้เพิ่มองค์ประกอบ 6 ประการข้างต้น
ต่อไปนี้เป็นรหัสที่สมบูรณ์ในการประกาศและเริ่มต้นรายการใน C# -
ตัวอย่าง
using System;
using System.Collections.Generic;
class Program {
static void Main() {
// Initializing collections
List<string> myList = new List<string>() {
"one",
"two",
"three",
"four",
"five",
"size"
};
Console.WriteLine(myList.Count);
}
} ผลลัพธ์
6