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

Lấy tập hợp key trong StringDictionary C#

Giới thiệu

Để lấy tập hợp các key trong StringDictionary, sử dụng thuộc tính Keys trả về ICollection. StringDictionary là dictionary chuyên biệt cho key và value đều là string, không phân biệt chữ hoa/thường cho key (case-insensitive).

Ví dụ 1: Hai StringDictionary, lấy keys của dict2

using System;
using System.Collections;
using System.Collections.Specialized;

public class Demo {
    public static void Main() {
        StringDictionary strDict1 = new StringDictionary();
        strDict1.Add("U", "Electronics");
        strDict1.Add("V", "Toys");
        strDict1.Add("W", "Books");
        strDict1.Add("X", "Accessories");

        Console.WriteLine("StringDictionary1 elements...");
        foreach(DictionaryEntry entry in strDict1) {
            Console.WriteLine(entry.Key + " " + entry.Value);
        }
        Console.WriteLine("StringDictionary1 có key 'G'? " + strDict1.ContainsKey("G"));

        StringDictionary strDict2 = new StringDictionary();
        strDict2.Add("A", "John");
        strDict2.Add("B", "Andy");
        strDict2.Add("C", "Tim");
        strDict2.Add("D", "Ryan");
        strDict2.Add("E", "Kevin");
        strDict2.Add("F", "Katie");
        strDict2.Add("G", "Brad");

        Console.WriteLine("\nStringDictionary2 elements...");
        foreach(DictionaryEntry entry in strDict2) {
            Console.WriteLine(entry.Key + " " + entry.Value);
        }

        Console.WriteLine("\nTập hợp key (StringDictionary2)...");
        string[] keyArray = new string[strDict2.Count];
        strDict2.Keys.CopyTo(keyArray, 0);
        for (int i = 0; i < strDict2.Count; i++) {
            Console.WriteLine("Key " + (i+1) + " = " + keyArray[i]);
        }

        Console.WriteLine("\nDict2 bằng Dict1? = " + strDict2.Equals(strDict1));
        Console.WriteLine("StringDictionary2 có key 'B'? " + strDict2.ContainsKey("B"));
    }
}

Đầu ra ví dụ 1

StringDictionary1 elements...
X Accessories
U Electronics
V Toys
W Books
StringDictionary1 có key 'G'? False

StringDictionary2 elements...
A John
B Andy
C Tim
D Ryan
E Kevin
F Katie
G Brad

Tập hợp key (StringDictionary2)...
Key 1 = A
Key 2 = B
Key 3 = C
Key 4 = D
Key 5 = E
Key 6 = F
Key 7 = G

Dict2 bằng Dict1? = False
StringDictionary2 có key 'B'? True

Ví dụ 2: Lấy keys và values cùng lúc

using System;
using System.Collections;
using System.Collections.Specialized;

public class Demo {
    public static void Main() {
        StringDictionary strDict = new StringDictionary();
        strDict.Add("S", "Home Appliances");
        strDict.Add("T", "Smart Wearable Tech");
        strDict.Add("U", "Electronics");
        strDict.Add("V", "Toys");
        strDict.Add("W", "Books");
        strDict.Add("X", "Accessories");

        Console.WriteLine("StringDictionary elements...");
        foreach(DictionaryEntry entry in strDict) {
            Console.WriteLine(entry.Key + " " + entry.Value);
        }

        Console.WriteLine("\nTập hợp key và value...");
        string[] keyArray = new string[strDict.Count];
        strDict.Keys.CopyTo(keyArray, 0);
        for (int i = 0; i < strDict.Count; i++) {
            Console.WriteLine("Key " + (i+1) + " = " + keyArray[i] + ", Value " + (i+1) + " = " + strDict[keyArray[i]]);
        }

        Console.WriteLine("\nStringDictionary có key 'B'? " + strDict.ContainsKey("B"));
    }
}

Đầu ra ví dụ 2

StringDictionary elements...
X Accessories
S Home Appliances
T Smart Wearable Tech
U Electronics
V Toys
W Books

Tập hợp key và value...
Key 1 = X, Value 1 = Accessories
Key 2 = S, Value 2 = Home Appliances
Key 3 = T, Value 3 = Smart Wearable Tech
Key 4 = U, Value 4 = Electronics
Key 5 = V, Value 5 = Toys
Key 6 = W, Value 6 = Books

StringDictionary có key 'B'? False

Đặc điểm StringDictionary

  • Key: string, không phân biệt chữ hoa/thường (case-insensitive). "A" và "a" là cùng key.
  • Value: string (không cho phép null, ném ArgumentNullException).
  • Kế thừa từ Hashtable, nội bộ dùng Hashtable.
  • Namespace: System.Collections.Specialized.
  • Không generic, đã cũ (legacy). Khuyến nghị dùng Dictionary<string, string> với StringComparer.OrdinalIgnoreCase.

Các thành viên quan trọng

Thành viênKiểuMô tả
KeysICollectionTập hợp key (case-insensitive)
ValuesICollectionTập hợp value
Item[string key]stringGetter/setter value
Add(key, value)voidThêm cặp (key unique, không phân biệt hoa/thường)
ContainsKey(key)boolKiểm tra key tồn tại
ContainsValue(value)boolKiểm tra value tồn tại
Remove(key)voidXóa theo key
Clear()voidXóa tất cả

Thay thế hiện đại: Dictionary<string, string>

// Case-insensitive dictionary hiện đại
var dict = new Dictionary(StringComparer.OrdinalIgnoreCase);
dict["A"] = "John";
dict["a"] = "Jane"; // Ghi đè "A" vì case-insensitive

// Lấy keys
foreach (var key in dict.Keys) { ... }
// Hoặc
string[] keys = dict.Keys.ToArray();

Lưu ý

  • StringDictionary.Keys trả về key ở dạng chữ thường (lowercase) do nội bộ chuẩn hóa.
  • Equals() của StringDictionary cũng là reference equality.
  • Dùng CopyTo để copy keys sang mảng string[].