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

Kiểm tra SortedDictionary có chứa khóa trong C#

Giới thiệu

SortedDictionary<TKey, TValue> (namespace System.Collections.Generic) là từ điển tự động sắp xếp theo khóa. Phương thức ContainsKey(TKey key) kiểm tra khóa tồn tại, trả về bool.

Ví dụ 1: Khóa kiểu int

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

public class Demo
{
    public static void Main()
    {
        SortedDictionary sortedDict = new SortedDictionary();
        sortedDict.Add(100, "Mobile");
        sortedDict.Add(200, "Laptop");
        sortedDict.Add(300, "Desktop");
        sortedDict.Add(400, "Speakers");
        sortedDict.Add(500, "Headphone");
        sortedDict.Add(600, "Earphone");

        Console.WriteLine("Các cặp khóa-giá trị SortedDictionary...");
        IDictionaryEnumerator demoEnum = sortedDict.GetEnumerator();
        while (demoEnum.MoveNext())
            Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);

        Console.WriteLine("\nSortedDictionary có khóa 200? = " + sortedDict.ContainsKey(200));
    }
}

Kết quả

Các cặp khóa-giá trị SortedDictionary...
Key = 100, Value = Mobile
Key = 200, Value = Laptop
Key = 300, Value = Desktop
Key = 400, Value = Speakers
Key = 500, Value = Headphone
Key = 600, Value = Earphone
SortedDictionary có khóa 200? = True

Ví dụ 2: Khóa kiểu string

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

public class Demo
{
    public static void Main()
    {
        SortedDictionary sortedDict = new SortedDictionary();
        sortedDict.Add("A", "John");
        sortedDict.Add("B", "Andy");
        sortedDict.Add("C", "Tim");
        sortedDict.Add("D", "Ryan");
        sortedDict.Add("E", "Kevin");
        sortedDict.Add("F", "Katie");
        sortedDict.Add("G", "Brad");

        Console.WriteLine("Các cặp khóa-giá trị SortedDictionary...");
        IDictionaryEnumerator demoEnum = sortedDict.GetEnumerator();
        while (demoEnum.MoveNext())
            Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);

        Console.WriteLine("\nSortedDictionary có khóa 'F'? = " + sortedDict.ContainsKey("F"));
    }
}

Kết quả

Các cặp khóa-giá trị SortedDictionary...
Key = A, Value = John
Key = B, Value = Andy
Key = C, Value = Tim
Key = D, Value = Ryan
Key = E, Value = Kevin
Key = F, Value = Katie
Key = G, Value = Brad
SortedDictionary có khóa 'F'? = True

Đặc điểm

  • Sắp xếp theo khóa tăng dần (dùng comparer mặc định hoặc custom).
  • Truy xuất, thêm, xóa O(log n) do dùng cây nhị phân cân bằng (Red-Black tree).
  • ContainsKey nhanh hơn ContainsValue (O(log n) vs O(n)).