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

Phương thức ContainsKey trong C# Dictionary


Giới thiệu

Phương thức ContainsKey() của Dictionary<TKey, TValue> kiểm tra xem một khóa có tồn tại trong từ điển hay không. Trả về true nếu khóa tồn tại, ngược lại false. Độ phức tạp O(1).

Ví dụ cơ bản

var dict = new Dictionary()
{
    {"TV", 1},
    {"Home Theatre", 2},
    {"Amazon Alexa", 3},
    {"Google Home", 5},
    {"Laptop", 5},
    {"Bluetooth Speaker", 6}
};

if (dict.ContainsKey("Laptop"))
{
    Console.WriteLine(dict["Laptop"]); // 5
}

Ví dụ hoàn chỉnh

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        var dict = new Dictionary()
        {
            {"TV", 1},
            {"Home Theatre", 2},
            {"Amazon Alexa", 3},
            {"Google Home", 5},
            {"Laptop", 5},
            {"Bluetooth Speaker", 6}
        };

        if (dict.ContainsKey("Laptop"))
        {
            Console.WriteLine(dict["Laptop"]);
        }
        if (dict.ContainsKey("Amazon Alexa"))
        {
            Console.WriteLine(dict["Amazon Alexa"]);
        }
    }
}

Kết quả

5
3

So sánh với TryGetValue()

Phương thứcLượt tra cứuTrả về giá trịPhù hợp khi
ContainsKey + Indexer2 lầnKhông (phải truy xuất riêng)Chỉ cần kiểm tra tồn tại
TryGetValue1 lầnCó (qua out parameter)Cần cả kiểm tra và lấy giá trị

Ví dụ TryGetValue (khuyên dùng)

if (dict.TryGetValue("Laptop", out int value))
{
    Console.WriteLine(value); // 5
}

Lưu ý

  • ContainsKey(null) ném ArgumentNullException nếu TKey là kiểu tham chiếu.
  • Không phân biệt chữ hoa/thường cho string key mặc định. Dùng StringComparer.OrdinalIgnoreCase khi khởi tạo Dictionary nếu cần.