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

Kiểm tra item tồn tại trong List C#

Kiểm tra tồn tại trong List<T>: Contains (O(n)), Exists (predicate), Any (LINQ), BinarySearch (O(log n) - cần sorted).

Ví dụ minh họa

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        var list = new List { "Lawrence", "Adams", "Pitt", "Tom" };
        
        Console.WriteLine("List: " + string.Join(", ", list));
        
        // Cách 1: Contains - exact match, O(n)
        bool hasAdams = list.Contains("Adams");
        Console.WriteLine($"Contains('Adams'): {hasAdams}"); // True
        
        // Cách 2: Exists - predicate, O(n)
        bool hasLong = list.Exists(s => s.Length > 5);
        Console.WriteLine($"Exists(len>5): {hasLong}"); // True (Lawrence)
        
        // Cách 3: LINQ Any
        bool hasP = list.Any(s => s.StartsWith("P"));
        Console.WriteLine($"Any(StartsWith P): {hasP}"); // True (Pitt)
        
        // Cách 4: BinarySearch - O(log n) - CẦN SORTED LIST
        var sorted = new List(list);
        sorted.Sort();
        int index = sorted.BinarySearch("Pitt");
        Console.WriteLine($"\nSorted: {string.Join(", ", sorted)}");
        Console.WriteLine($"BinarySearch('Pitt'): index = {index}"); // >= 0 nếu tìm thấy
        
        // Không tìm thấy
        int notFound = sorted.BinarySearch("Zzz");
        Console.WriteLine($"BinarySearch('Zzz'): {notFound}"); // Negative (~index to insert)
    }
}

Kết quả đầu ra

List: Lawrence, Adams, Pitt, Tom
Contains('Adams'): True
Exists(len>5): True
Any(StartsWith P): True

Sorted: Adams, Lawrence, Pitt, Tom
BinarySearch('Pitt'): index = 2
BinarySearch('Zzz'): -4

So sánh hiệu năng

Phương thứcPhức tạpDùng khi
ContainsO(n)Exact match, list nhỏ
Exists/AnyO(n)Điều kiện phức tạp
BinarySearchO(log n)List LỚN, ĐÃ SORT
HashSet.ContainsO(1)Tra cứu nhiều lần, chuyển sang HashSet

Mẹo: Nếu check tồn tại nhiều lần → chuyển List sang HashSet một lần, sau đó dùng Contains O(1).