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

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


Phương thức Dictionary.ContainsKey() trong C# kiểm tra xem Dictionary<TKey, TValue> có chứa khóa (key) được chỉ định hay không.

Cú pháp

public bool ContainsKey(TKey key);

Tham số:

  • key: Khóa cần tìm kiếm

Ví dụ 1: Khóa tồn tại

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        Dictionary dict = new Dictionary();
        dict.Add("One", "John");
        dict.Add("Two", "Tom");
        dict.Add("Three", "Jacob");
        dict.Add("Four", "Kevin");
        dict.Add("Five", "Nathan");
        
        Console.WriteLine("Số lượng phần tử = " + dict.Count);
        Console.WriteLine("\nCác cặp Key/Value...");
        
        foreach (KeyValuePair res in dict)
            Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
        
        if (dict.ContainsKey("Three"))
            Console.WriteLine("Tìm thấy khóa!");
        else
            Console.WriteLine("Khóa không có trong dictionary!");
        
        dict.Clear();
        Console.WriteLine("Đã xóa các cặp Key/Value...");
        Console.WriteLine("Số lượng phần tử hiện tại = " + dict.Count);
    }
}

Kết quả

Số lượng phần tử = 5
Các cặp Key/Value...
Key = One, Value = John
Key = Two, Value = Tom
Key = Three, Value = Jacob
Key = Four, Value = Kevin
Key = Five, Value = Nathan
Tìm thấy khóa!
Đã xóa các cặp Key/Value...
Số lượng phần tử hiện tại = 0

Ví dụ 2: Khóa không tồn tại

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        Dictionary dict = new Dictionary();
        dict.Add("One", "John");
        dict.Add("Two", "Tom");
        dict.Add("Three", "Jacob");
        dict.Add("Four", "Kevin");
        dict.Add("Five", "Nathan");
        
        Console.WriteLine("Số lượng phần tử = " + dict.Count);
        Console.WriteLine("\nCác cặp Key/Value...");
        
        foreach (KeyValuePair res in dict)
            Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
        
        if (dict.ContainsKey("mykey"))
            Console.WriteLine("Tìm thấy khóa!");
        else
            Console.WriteLine("Khóa không có trong dictionary!");
        
        dict.Clear();
        Console.WriteLine("Đã xóa các cặp Key/Value...");
        Console.WriteLine("Số lượng phần tử hiện tại = " + dict.Count);
    }
}

Kết quả

Số lượng phần tử = 5
Các cặp Key/Value...
Key = One, Value = John
Key = Two, Value = Tom
Key = Three, Value = Jacob
Key = Four, Value = Kevin
Key = Five, Value = Nathan
Khóa không có trong dictionary!
Đã xóa các cặp Key/Value...
Số lượng phần tử hiện tại = 0

Mẹo: Luôn dùng ContainsKey trước khi truy cập dict[key] để tránh KeyNotFoundException. Hoặc dùng TryGetValue để kiểm tra và lấy giá trị cùng lúc.