Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Đếm tổng số phần tử trong List C#

Ví dụ 1

Sử dụng thuộc tính Count để đếm phần tử:

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("Các phần tử List1...");
        foreach (string res in list) {
            Console.WriteLine(res);
        }
        
        Console.WriteLine("\nSố phần tử trong list = " + list.Count);
        list.Clear();
        Console.WriteLine("\nSố phần tử trong list (cập nhật) = " + list.Count);
    }
}

Kết quả

Các phần tử List1...
One
Two
Three
Four
Five
Số phần tử trong list = 5
Số phần tử trong list (cập nhật) = 0

Ví dụ 2

Đếm phần tử và sử dụng 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("Số phần tử trong list = " + list.Count);
        Console.WriteLine("Enumerator lặp qua các phần tử...");
        
        List<string>.Enumerator demoEnum = list.GetEnumerator();
        while (demoEnum.MoveNext()) {
            string res = demoEnum.Current;
            Console.WriteLine(res);
        }
        
        list.Add("600");
        list.Add("700");
        Console.WriteLine("Số phần tử trong list (cập nhật) = " + list.Count);
    }
}

Kết quả

Số phần tử trong list = 5
Enumerator lặp qua các phần tử...
100
200
300
400
500
Số phần tử trong list (cập nhật) = 7