ภาพรวม
เมธอด Count() ใน LINQ ใช้นับจำนวนองค์ประกอบในลำดับ (sequence) คืนค่า int
รูปแบบการใช้งาน
string[] arr = { "Java", "C++", "Python" };
int count = arr.AsQueryable().Count(); // หรือ arr.Count()
ตัวอย่างโค้ดเต็ม
using System;
using System.Linq;
using System.Collections.Generic;
class Demo
{
static void Main()
{
string[] arr = { "Java", "C++", "Python" };
int arr_count = arr.AsQueryable().Count();
Console.WriteLine("Count of arrays: {0}", arr_count);
}
}
ผลลัพธ์
Count of arrays: 3
ตัวเลือกเพิ่มเติม
Count(predicate)- นับเฉพาะองค์ประกอบที่ตรงเงื่อนไข:arr.Count(s => s.Length > 3)- สำหรับ
List<T>และอาร์เรย์ ใช้คุณสมบัติ.Countหรือ.Lengthโดยตรง เร็วกว่า LongCount()- คืนค่าlongสำหรับลำดับขนาดใหญ่มาก