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

Lấy enumerator cho phạm vi phần tử trong ArrayList C#

Giới thiệu

Phương thức GetEnumerator(int index, int count) của ArrayList trả về IEnumerator duyệt qua một đoạn con (range) bắt đầu từ index với độ dài count.

Ví dụ 1: Duyệt phạm vi index 1, count 3

using System;
using System.Collections;

public class Demo
{
    public static void Main()
    {
        ArrayList arrList = new ArrayList();
        arrList.Add(100);
        arrList.Add(200);
        arrList.Add(300);
        arrList.Add(400);
        arrList.Add(500);

        Console.WriteLine("Hiển thị phần tử trong phạm vi...");
        IEnumerator demoEnum = arrList.GetEnumerator(1, 3);
        while (demoEnum.MoveNext())
        {
            object ob = demoEnum.Current;
            Console.WriteLine(ob);
        }
    }
}

Kết quả

Hiển thị phần tử trong phạm vi...
200
300
400

Ví dụ 2: Hai phạm vi khác nhau

using System;
using System.Collections;

public class Demo
{
    public static void Main()
    {
        ArrayList arrList = new ArrayList();
        arrList.Add("Andy");
        arrList.Add("Katie");
        arrList.Add("Taylor");
        arrList.Add("Steve");
        arrList.Add("Nathan");
        arrList.Add("Carl");
        arrList.Add("Mark");
        arrList.Add("Amy");
        arrList.Add("Jacob");
        arrList.Add("John");

        Console.WriteLine("Hiển thị phần tử trong phạm vi...");
        IEnumerator demoEnum = arrList.GetEnumerator(1, 3);
        while (demoEnum.MoveNext())
        {
            object ob = demoEnum.Current;
            Console.WriteLine(ob);
        }

        Console.WriteLine("Hiển thị phần tử trong phạm vi...");
        demoEnum = arrList.GetEnumerator(3, 5);
        while (demoEnum.MoveNext())
        {
            object ob = demoEnum.Current;
            Console.WriteLine(ob);
        }
    }
}

Kết quả

Hiển thị phần tử trong phạm vi...
Katie
Taylor
Steve
Hiển thị phần tử trong phạm vi...
Steve
Nathan
Carl
Mark
Amy

Lưu ý

  • index là chỉ số 0-based.
  • Nếu index + count > Count sẽ ném ArgumentOutOfRangeException.
  • Enumerator này chỉ đọc, không hỗ trợ Reset() về đầu phạm vi.
  • List<T> không có overload này; dùng LINQ Skip(index).Take(count).