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

การได้ Enumerator สำหรับช่วงข้อมูลใน ArrayList ใน C#

ArrayList มี overload ของ GetEnumerator(int index, int count) ที่คืน Enumerator สำหรับวนลูปเฉพาะช่วง (range) ของข้อมูล เริ่มจาก index จำนวน count รายการ

ตัวอย่างโค้ดที่ 1: ตัวเลข

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("Display elements in a range...");
        IEnumerator demoEnum = arrList.GetEnumerator(1, 3); // index 1, count 3
        while (demoEnum.MoveNext())
        {
            object ob = demoEnum.Current;
            Console.WriteLine(ob);
        }
    }
}

ผลลัพธ์

Display elements in a range...
200
300
400

ตัวอย่างโค้ดที่ 2: สตริง หลายช่วง

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("Display elements in a range...");
        IEnumerator demoEnum = arrList.GetEnumerator(1, 3); // index 1, count 3
        while (demoEnum.MoveNext())
        {
            object ob = demoEnum.Current;
            Console.WriteLine(ob);
        }

        Console.WriteLine("Display elements in a range...");
        demoEnum = arrList.GetEnumerator(3, 5); // index 3, count 5
        while (demoEnum.MoveNext())
        {
            object ob = demoEnum.Current;
            Console.WriteLine(ob);
        }
    }
}

ผลลัพธ์

Display elements in a range...
Katie
Taylor
Steve
Display elements in a range...
Steve
Nathan
Carl
Mark
Amy

ข้อสังเกต

  • GetEnumerator(index, count) คืน IEnumerator (non-generic)
  • index = ดัชนีเริ่มต้น (0-based)
  • count = จำนวนรายการที่จะวน
  • จะโยน ArgumentOutOfRangeException หาก index หรือ count ไม่ถูกต้อง
  • Enumerator นี้ ไม่รองรับ Reset() กลับไปจุดเริ่มต้นของช่วงได้

เปรียบเทียบกับ List<T>

List<T> ไม่มี GetEnumerator(index, count) ตรงๆ แต่สามารถทำได้ง่ายด้วย LINQ:


using System.Linq;

var list = new List { 100, 200, 300, 400, 500 };
var range = list.Skip(1).Take(3); // index 1, count 3
foreach (var item in range) Console.WriteLine(item);
// Output: 200, 300, 400

ArrayList vs List<T> - สรุป

คุณสมบัติArrayListList<T>
GetEnumerator(range)มี built-inใช้ LINQ (Skip/Take)
Type Safetyไม่มีมี
PerformanceBoxing overheadไม่มี boxing
แนะนำLegacy onlyใช้ในโค้ดใหม่