Đầu tiên, đặt một bộ sưu tập Từ điển với các phần tử.
Dictionary<int, string> d = new Dictionary<int, string>() {
{1,"Applianes"},
{2, "Clothing"},
{3,"Toys"},
{4,"Footwear"},
{5, "Accessories"}
}; Bây giờ, giả sử bạn cần kiểm tra xem khóa 5 có tồn tại hay không. Để làm điều đó, hãy sử dụng phương thức ContainsKey (). Nó trả về True nếu tìm thấy khóa.
d.ContainsKey(5);
Hãy cho chúng tôi xem mã hoàn chỉnh.
Ví dụ
using System;
using System.Collections.Generic;
public class Program {
public static void Main() {
Dictionary<int, string> d = new Dictionary<int, string>() {
{1,"Electronics"},
{2, "Clothing"},
{3,"Toys"},
{4,"Footwear"},
{5, "Accessories"}
};
foreach (KeyValuePair<int, string> ele in d) {
Console.WriteLine("Key = {0}, Value = {1}", ele.Key, ele.Value);
}
Console.WriteLine("Key 5 exists? "+d.ContainsKey(5));
}
} Đầu ra
Key = 1, Value = Electronics Key = 2, Value = Clothing Key = 3, Value = Toys Key = 4, Value = Footwear Key = 5, Value = Accessories Key 5 exists? True