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

Thuộc tính SortedDictionary.Item[] (Indexer) trong C#

Thuộc tính indexer SortedDictionary<TKey, TValue>.Item[] (cú pháp dict[key]) trong C# được dùng để lấy hoặc đặt giá trị liên kết với khóa được chỉ định.

Cú pháp

public TValue this[TKey key] { get; set; }
  • get: Trả về giá trị của key. Ném KeyNotFoundException nếu key không tồn tại.
  • set: Thêm cặp key-value mới, hoặc cập nhật value nếu key đã tồn tại.

Ví dụ 1: Truy cập, cập nhật, Clear

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

public class Demo
{
    public static void Main()
    {
        SortedDictionary sortedDict = new SortedDictionary();

        sortedDict.Add(1, "One");
        sortedDict.Add(2, "Two");
        sortedDict.Add(3, "Three");
        sortedDict.Add(4, "Four");
        sortedDict.Add(5, "Five");
        sortedDict.Add(6, "Six");

        Console.WriteLine("Các cặp key-value...");
        IDictionaryEnumerator demoEnum = sortedDict.GetEnumerator();
        while (demoEnum.MoveNext())
        {
            Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
        }

        Console.WriteLine("Số lượng = " + sortedDict.Count);

        sortedDict.Add(7, "Seven");
        sortedDict.Add(8, "Eight");

        Console.WriteLine("\nCác cặp key-value SAU KHI CẬP NHẬT...");
        demoEnum = sortedDict.GetEnumerator();
        while (demoEnum.MoveNext())
        {
            Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
        }

        Console.WriteLine("Số lượng (cập nhật) = " + sortedDict.Count);

        // Truy cập qua indexer (get)
        Console.WriteLine("Giá trị key 5 = " + sortedDict[5]); // Five

        // Xóa tất cả
        sortedDict.Clear();
        Console.WriteLine("\nSố lượng sau Clear = " + sortedDict.Count); // 0
    }
}

Kết quả

Key = 1, Value = One
Key = 2, Value = Two
Key = 3, Value = Three
Key = 4, Value = Four
Key = 5, Value = Five
Key = 6, Value = Six
Số lượng = 6

Các cặp key-value SAU KHI CẬP NHẬT...
Key = 1, Value = One
Key = 2, Value = Two
Key = 3, Value = Three
Key = 4, Value = Four
Key = 5, Value = Five
Key = 6, Value = Six
Key = 7, Value = Seven
Key = 8, Value = Eight
Số lượng (cập nhật) = 8
Giá trị key 5 = Five
Số lượng sau Clear = 0

Ví dụ 2: Cập nhật value qua indexer (set)

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

public class Demo
{
    public static void Main()
    {
        SortedDictionary sortedDict = new SortedDictionary();

        sortedDict.Add(1, "SUV");
        sortedDict.Add(2, "MUV");
        sortedDict.Add(3, "Utility Vehicle");
        sortedDict.Add(4, "AUV");
        sortedDict.Add(5, "Hatchback");
        sortedDict.Add(6, "Convertible");

        Console.WriteLine("Các cặp key-value...");
        IDictionaryEnumerator demoEnum = sortedDict.GetEnumerator();
        while (demoEnum.MoveNext())
        {
            Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
        }

        Console.WriteLine("Số lượng = " + sortedDict.Count);

        sortedDict.Add(7, "Seven");
        sortedDict.Add(8, "Eight");

        Console.WriteLine("\nCác cặp key-value SAU KHI CẬP NHẬT...");
        demoEnum = sortedDict.GetEnumerator();
        while (demoEnum.MoveNext())
        {
            Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
        }

        Console.WriteLine("Số lượng (cập nhật) = " + sortedDict.Count);

        // Get
        Console.WriteLine("Giá trị key 5 = " + sortedDict[5]); // Hatchback

        // Set (cập nhật)
        sortedDict[5] = "Crossover";
        Console.WriteLine("Giá trị key 5 (cập nhật) = " + sortedDict[5]); // Crossover

        sortedDict.Clear();
        Console.WriteLine("\nSố lượng sau Clear = " + sortedDict.Count);
    }
}

Kết quả

Key = 1, Value = SUV
Key = 2, Value = MUV
Key = 3, Value = Utility Vehicle
Key = 4, Value = AUV
Key = 5, Value = Hatchback
Key = 6, Value = Convertible
Số lượng = 6

Các cặp key-value SAU KHI CẬP NHẬT...
Key = 1, Value = SUV
Key = 2, Value = MUV
Key = 3, Value = Utility Vehicle
Key = 4, Value = AUV
Key = 5, Value = Hatchback
Key = 6, Value = Convertible
Key = 7, Value = Seven
Key = 8, Value = Eight
Số lượng (cập nhật) = 8
Giá trị key 5 = Hatchback
Giá trị key 5 (cập nhật) = Crossover
Số lượng sau Clear = 0

Indexer vs Add() vs TryGetValue()

Phép toán Hành vi Ngoại lệ nếu key không tồn tại
dict[key] (get) Trả về value KeyNotFoundException
dict[key] = val (set) Thêm mới hoặc cập nhật Không (luôn thành công)
dict.Add(key, val) Chỉ thêm mới ArgumentException nếu key tồn tại
dict.TryGetValue(key, out val) Thử lấy, an toàn Không (trả về false)

Lưu ý

  • Indexer set thay thế Add khi không chắc key đã tồn tại.
  • Dùng TryGetValue cho hiệu suất tốt hơn (tránh exception handling).
  • SortedDictionary giữ key tự động sắp xếp sau mọi thao tác Add/Set/Remove.