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

Lấy enumerator duyệt StringCollection trong C#

Giới thiệu

Lớp StringCollection trong namespace System.Collections.Specialized là collection chuyên dụng cho chuỗi. Phương thức GetEnumerator() trả về StringEnumerator để duyệt các phần tử. Hiện nay khuyến nghị dùng List<string> hoặc Collection<string> thay thế.

Ví dụ 1

using System;
using System.Collections.Specialized;

public class Demo
{
    public static void Main()
    {
        StringCollection stringCol = new StringCollection();
        String[] arr = new String[] { "100", "200", "300", "400", "500" };

        Console.WriteLine("Các phần tử mảng...");
        foreach (string res in arr)
        {
            Console.WriteLine(res);
        }

        stringCol.AddRange(arr);

        Console.WriteLine("StringCollection có chứa '800'? = " + stringCol.Contains("800"));
        Console.WriteLine("Tổng số phần tử = " + stringCol.Count);
        Console.WriteLine("Duyệt StringCollection = " + stringCol.Count);

        StringEnumerator myEnum = stringCol.GetEnumerator();
        while (myEnum.MoveNext())
        {
            Console.WriteLine(myEnum.Current);
        }
    }
}

Kết quả

Các phần tử mảng...
100
200
300
400
500
StringCollection có chứa '800'? = False
Tổng số phần tử = 5
Duyệt StringCollection = 5
100
200
300
400
500

Ví dụ 2

using System;
using System.Collections.Specialized;

public class Demo
{
    public static void Main()
    {
        StringCollection stringCol = new StringCollection();
        stringCol.Add("10");
        stringCol.Add("20");
        stringCol.Add("30");
        stringCol.Add("40");
        stringCol.Add("50");
        stringCol.Add("60");
        stringCol.Add("70");
        stringCol.Add("80");
        stringCol.Add("90");
        stringCol.Add("100");

        Console.WriteLine("Các phần tử...");
        foreach (string res in stringCol)
        {
            Console.WriteLine(res);
        }

        Console.WriteLine("Duyệt StringCollection với Enumerator...");
        StringEnumerator myEnum = stringCol.GetEnumerator();
        while (myEnum.MoveNext())
        {
            Console.WriteLine(myEnum.Current);
        }
    }
}

Kết quả

Các phần tử...
10
20
30
40
50
60
70
80
90
100
Duyệt StringCollection với Enumerator...
10
20
30
40
50
60
70
80
90
100

Lưu ý quan trọng

  • StringCollection là lớp legacy (hệ thống cũ), trong .NET mới nên dùng List<string>.
  • StringEnumerator chỉ hỗ trợ MoveNext() và Current, không hỗ trợ Reset().
  • Duyệt bằng foreach tự động sử dụng enumerator và an toàn hơn.
  • AddRange() thêm nhiều phần tử từ mảng hoặc collection khác.