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

การนับจำนวนสมาชิกทั้งหมดใน List ใน C#

ภาพรวม

คุณสมบัติ List<T>.Count คืนจำนวนสมาชิกใน List ทันที (O(1)) ต่างจาก Count() ของ LINQ ที่ต้องวนลูป

ตัวอย่างที่ 1: นับจำนวน แล้วล้างด้วย Clear()

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main(String[] args)
    {
        List<String> list = new List<String>();
        list.Add("One");
        list.Add("Two");
        list.Add("Three");
        list.Add("Four");
        list.Add("Five");

        Console.WriteLine("Elements in List1...");
        foreach (string res in list)
        {
            Console.WriteLine(res);
        }

        Console.WriteLine("\nCount of elements in list = " + list.Count);
        list.Clear();
        Console.WriteLine("\nCount of elements in list (updated) = " + list.Count);
    }
}

ผลลัพธ์

Elements in List1...
One
Two
Three
Four
Five
Count of elements in list = 5
Count of elements in list (updated) = 0

ตัวอย่างที่ 2: ใช้ Enumerator วนลูป แล้วเพิ่มสมาชิกและนับใหม่

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main(String[] args)
    {
        List<String> list = new List<String>();
        list.Add("100");
        list.Add("200");
        list.Add("300");
        list.Add("400");
        list.Add("500");

        Console.WriteLine("Count of elements in the list = " + list.Count);
        Console.WriteLine("Enumerator iterates through the list elements...");
        List<string>.Enumerator demoEnum = list.GetEnumerator();
        while (demoEnum.MoveNext())
        {
            string res = demoEnum.Current;
            Console.WriteLine(res);
        }

        list.Add("600");
        list.Add("700");
        Console.WriteLine("Count of elements in the list (updated) = " + list.Count);
    }
}

ผลลัพธ์

Count of elements in the list = 5
Enumerator iterates through the list elements...
100
200
300
400
500
Count of elements in the list (updated) = 7

สรุป

  • ใช้ list.Count สำหรับจำนวนสมาชิก (property)
  • Clear() ลบทั้งหมด ทำให้ Count = 0
  • Enumerator แบบ struct List<T>.Enumerator ใช้ได้แต่ควรใช้ foreach แทน