ใช้ Property Count ของ List เพื่อนับจำนวนรายการ
ตัวอย่าง
List<string> myList = new List<string>()
{
"electronics",
"clothing",
"appliances",
"accessories"
};
int count = myList.Count; // 4
โค้ดตัวอย่างเต็ม
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<string> myList = new List<string>()
{
"electronics",
"clothing",
"appliances",
"accessories"
};
Console.WriteLine("Count: " + myList.Count);
}
}
ผลลัพธ์
Count: 4
หมายเหตุ
Countเป็น Property (ไม่ใช่เมธอด) - ใช้myList.Countไม่ใช่myList.Count()Count()เป็น Extension Method ของ LINQ (ช้ากว่า)- Array ใช้
LengthProperty แทน