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

Lấy số lượng chuỗi trong StringCollection C#

Giới thiệu

Để lấy số lượng chuỗi trong StringCollection, bạn sử dụng thuộc tính Count. Thuộc tính này trả về số phần tử hiện có trong tập hợp.

Ví dụ 1: StringCollection từ mảng 8 phần tử

using System;
using System.Collections.Specialized;

public class Demo
{
    public static void Main()
    {
        StringCollection strCol = new StringCollection();
        String[] strArr = new String[] { "A", "B", "C", "D", "E", "F", "G", "H" };

        Console.WriteLine("Các phần tử của StringCollection...");
        foreach (string str in strArr)
            Console.WriteLine(str);

        strCol.AddRange(strArr);
        Console.WriteLine("Phần tử tại chỉ số 5 = " + strCol[5]);
        Console.WriteLine("Số lượng chuỗi trong StringCollection = " + strCol.Count);
    }
}

Kết quả

Các phần tử của StringCollection...
A
B
C
D
E
F
G
H
Phần tử tại chỉ số 5 = F
Số lượng chuỗi trong StringCollection = 8

Ví dụ 2: StringCollection từ mảng 5 phần tử

using System;
using System.Collections.Specialized;

public class Demo
{
    public static void Main()
    {
        StringCollection strCol = new StringCollection();
        String[] strArr = new String[] { "10", "20", "30", "40", "50" };

        Console.WriteLine("Các phần tử của StringCollection...");
        foreach (string str in strArr)
            Console.WriteLine(str);

        strCol.AddRange(strArr);
        Console.WriteLine("Số lượng chuỗi trong StringCollection = " + strCol.Count);
    }
}

Kết quả

Các phần tử của StringCollection...
10
20
30
40
50
Số lượng chuỗi trong StringCollection = 5

Lưu ý: StringCollection chỉ chứa chuỗi, cho phép trùng lặp, hỗ trợ truy xuất bằng chỉ số (indexer). Thuộc tính Count có độ phức tạp O(1).