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

วิธีนับจำนวนรายการใน C# List

ใช้ 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 ใช้ Length Property แทน