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ức | Lượt tra cứu | Trả về giá trị | Phù hợp khi |
|---|---|---|---|
| ContainsKey + Indexer | 2 lần | Không (phải truy xuất riêng) | Chỉ cần kiểm tra tồn tại |
| TryGetValue | 1 lần | Có (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émArgumentNullExceptionnế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.OrdinalIgnoreCasekhi khởi tạo Dictionary nếu cần.