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

ตรวจสอบว่ามีสมาชิกใน ArrayList หรือไม่ใน C#

ภาพรวม

เมธอด ArrayList.Contains(Object) ตรวจสอบว่ามีสมาชิกเท่ากับออบเจ็กต์ที่ระบุลหรือไม่ คืน true/false

ตัวอย่าง 1: ตรวจสอบสตริง

using System;
using System.Collections;

public class Demo {
    public static void Main() {
        ArrayList list = new ArrayList();
        list.Add("One");
        list.Add("Two");
        list.Add("Three");
        list.Add("Four");
        list.Add("Five");
        list.Add("Six");
        list.Add("Seven");
        list.Add("Eight");

        Console.WriteLine("ArrayList elements...");
        foreach (string str in list) {
            Console.WriteLine(str);
        }

        Console.WriteLine("ArrayList is read-only? = " + list.IsReadOnly);
        Console.WriteLine("Does the element Six in the ArrayList? = " + list.Contains("Six"));
    }
}

ผลลัพธ์ตัวอย่าง 1

ArrayList elements...
One
Two
Three
Four
Five
Six
Seven
Eight
ArrayList is read-only? = False
Does the element Six in the ArrayList? = True

ตัวอย่าง 2: ตรวจสอบตัวเลข และใช้ GetEnumerator(range)

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);
        while (demoEnum.MoveNext()) {
            Object ob = demoEnum.Current;
            Console.WriteLine(ob);
        }

        Console.WriteLine("Does the element 1000 in the ArrayList? = " + arrList.Contains(1000));
    }
}

ผลลัพธ์ตัวอย่าง 2

Display elements in a range...
200
300
400
Does the element 1000 in the ArrayList? = False

สรุป

  • Contains ใช้ Equals เปรียบเทียบ
  • สำหรับ value type เปรียบเทียบค่า, reference type เปรียบเทียบอ้างอิง
  • GetEnumerator(index, count) วนเฉพาะช่วง