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

Kiểm tra phần tử có trong Collection trong C#

Giới thiệu

Lớp Collection<T> trong namespace System.Collections.ObjectModel là cơ sở cho các collection tùy chỉnh. Nó cung cấp phương thức Contains(T item) để kiểm tra sự tồn tại của phần tử (duyệt tuyến tính O(n)).

Ví dụ 1

using System;
using System.Collections.ObjectModel;

public class Demo
{
    public static void Main()
    {
        Collection col = new Collection();
        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("Các phần tử trong Collection...");
        foreach (int val in col)
        {
            Console.WriteLine(val);
        }

        Console.WriteLine("Collection có chứa phần tử 70? = " + col.Contains(70));
    }
}

Kết quả

Các phần tử trong Collection...
10
20
30
40
50
60
70
80
Collection có chứa phần tử 70? = True

Ví dụ 2

using System;
using System.Collections.ObjectModel;

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

        Console.WriteLine("Các phần tử trong Collection...");
        foreach (string val in col)
        {
            Console.WriteLine(val);
        }

        Console.WriteLine("Collection có chứa giá trị 'Bradley'? = " + col.Contains("Bradley"));
    }
}

Kết quả

Các phần tử trong Collection...
John
Gary
Tom
Brad
Katie
Andy
Nathan
Collection có chứa giá trị 'Bradley'? = False

Lưu ý quan trọng

  • Collection<T> là lớp cơ sở để tạo collection tùy chỉnh, cho phép override các phương thức như InsertItem, RemoveItem, SetItem, ClearItems.
  • Phương thức Contains() sử dụng EqualityComparer<T>.Default để so sánh.
  • Độ phức tạp tìm kiếm O(n) vì là danh sách tuyến tính.
  • Nếu cần tìm kiếm nhanh, cân nhắc HashSet<T> hoặc Dictionary<TKey, TValue>.