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

ดึงจำนวนองค์ประกอบใน Collection ใน C#

ภาพรวม

Collection<T> ใน namespace System.Collections.ObjectModel เป็นคลาสพื้นฐานสำหรับสร้างคอลเลกชันแบบกำหนดเอง คุณสมบัติ Count คืนค่าจำนวนองค์ประกอบที่อยู่ในคอลเลกชันปัจจุบัน

ตัวอย่างที่ 1: นับจำนวนและวนลูปด้วย Enumerator

using System;
using System.Collections.ObjectModel;

public class Demo
{
    public static void Main()
    {
        Collection<string> col = new Collection<string>();
        col.Add("Andy");
        col.Add("Kevin");
        col.Add("John");
        col.Add("Kevin");
        col.Add("Mary");
        col.Add("Katie");
        col.Add("Barry");
        col.Add("Nathan");
        col.Add("Mark");
        Console.WriteLine("Count of elements = " + col.Count);
        Console.WriteLine("Iterating through the collection...");
        var enumerator = col.GetEnumerator();
        while (enumerator.MoveNext())
        {
            Console.WriteLine(enumerator.Current);
        }
    }
}

ผลลัพธ์

Count of elements = 9
Iterating through the collection...
Andy
Kevin
John
Kevin
Mary
Katie
Barry
Nathan
Mark

ตัวอย่างที่ 2: นับจำนวน ตรวจสอบค่า และลบข้อมูล

using System;
using System.Collections.ObjectModel;

public class Demo
{
    public static void Main()
    {
        Collection<int> col = new Collection<int>();
        col.Add(10);
        col.Add(20);
        col.Add(30);
        col.Add(40);
        col.Add(50);
        col.Add(60);
        col.Add(70);
        col.Add(80);
        Console.WriteLine("Elements in the Collection...");
        foreach(int val in col)
        {
            Console.WriteLine(val);
        }
        Console.WriteLine("Does the collection has the element 70? = " + col.Contains(70));
        Console.WriteLine("Count of elements = " + col.Count);
        col.Clear();
        Console.WriteLine("Count of elements (updated) = " + col.Count);
    }
}

ผลลัพธ์

Elements in the Collection...
10
20
30
40
50
60
70
80
Does the collection has the element 70? = True
Count of elements = 8
Count of elements (updated) = 0

คำอธิบายเพิ่มเติม

  • Count เป็นคุณสมบัติอ่านอย่างเดียว (read-only) คืนค่า int
  • Contains() ตรวจสอบว่ามีองค์ประกอบที่ระบุอยู่หรือไม่ (ใช้การเปรียบเทียบเริ่มต้นของ T)
  • GetEnumerator() คืนค่า enumerator สำหรับการวนลูปแบบ manual
  • Collection<T> มักใช้เป็นคลาสฐานสำหรับสร้างคอลเลกชันเฉพาะเจาะจง (เช่น ObservableCollection)