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

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

บทความนี้สาธิตวิธีตรวจสอบว่า Collection<T> มีสมาชิก (element) ที่ระบุอยู่หรือไม่ โดยใช้เมธอด Contains() ใน C#

ตัวอย่างที่ 1: ตรวจสอบสมาชิกใน Collection ของจำนวนเต็ม (พบ)

using System;
using System.Collections.ObjectModel;

public class Demo
{
    public static void Main()
    {
        Collection<int> col = new Collection<int>();
        col.Add(10);
        col.Add(20);
        col.Add(30);
        col.Add(40);
        col.Add(50);
        col.Add(60);
        col.Add(70);
        col.Add(80);

        Console.WriteLine("Elements in the Collection...");
        foreach (int val in col)
        {
            Console.WriteLine(val);
        }

        Console.WriteLine("Does the collection has the element 70? = " + col.Contains(70));
    }
}

ผลลัพธ์

Elements in the Collection...
10
20
30
40
50
60
70
80
Does the collection has the element 70? = True

ตัวอย่างที่ 2: ตรวจสอบสมาชิกใน Collection ของสตริง (ไม่พบ)

using System;
using System.Collections.ObjectModel;

public class Demo
{
    public static void Main()
    {
        Collection<string> col = new Collection<string>();
        col.Add("John");
        col.Add("Gary");
        col.Add("Tom");
        col.Add("Brad");
        col.Add("Katie");
        col.Add("Andy");
        col.Add("Nathan");

        Console.WriteLine("Elements in the Collection...");
        foreach (string val in col)
        {
            Console.WriteLine(val);
        }

        Console.WriteLine("Does the collection has the value Bradley? = " + col.Contains("Bradley"));
    }
}

ผลลัพธ์

Elements in the Collection...
John
Gary
Tom
Brad
Katie
Andy
Nathan
Does the collection has the value Bradley? = False

สรุป

  • ใช้ Contains(T item) เพื่อตรวจสอบว่ามีสมาชิกอยู่ใน Collection<T> หรือไม่ — คืนค่า bool
  • Collection<T> (ใน namespace System.Collections.ObjectModel) เป็นคลาสฐานสำหรับสร้างคอลเลกชันแบบกำหนดเอง (custom collection)
  • Collection<T> รองรับ IList<T>, ICollection<T>, IEnumerable<T> และมีเมธอดเสมือน (virtual methods) ที่สามารถ override ได้ เช่น InsertItem, RemoveItem, SetItem, ClearItems
  • เมธอด Contains() ทำการค้นหาแบบ linear search — Complexity คือ O(n)
  • แตกต่างจาก List<T> ที่เป็น concrete implementation, Collection<T> ออกแบบมาเพื่อการสืบทอด (inheritance)