Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

วิธีดึงหรือตั้งค่าค่าที่เกี่ยวข้องกับคีย์ใน ListDictionary ใน C#

บทความนี้สาธิตวิธีการดึง (get) และตั้งค่า (set) ค่าที่เกี่ยวข้องกับคีย์ที่ระบุใน ListDictionary โดยใช้ indexer [key]

ตัวอย่างที่ 1: ดึงค่าจากคีย์ "C"

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

public class Demo
{
    public static void Main()
    {
        ListDictionary dict = new ListDictionary();
        dict.Add("A", "Books");
        dict.Add("B", "Electronics");
        dict.Add("C", "Appliances");
        dict.Add("D", "Pet Supplies");
        dict.Add("E", "Clothing");
        dict.Add("F", "Footwear");

        Console.WriteLine("Value associated with key C = " + dict["C"]);
    }
}

ผลลัพธ์

Value associated with key C = Appliances

ตัวอย่างที่ 2: ตั้งค่าใหม่ผ่าน Indexer

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

public class Demo
{
    public static void Main()
    {
        ListDictionary dict = new ListDictionary();
        dict.Add("A", "Books");
        dict.Add("B", "Electronics");
        dict.Add("C", "Appliances");
        dict.Add("D", "Pet Supplies");
        dict.Add("E", "Clothing");
        dict.Add("F", "Footwear");

        Console.WriteLine("Value associated with key C = " + dict["C"]);

        dict["C"] = "HDD"; // ตั้งค่าใหม่

        Console.WriteLine("Value associated with key C [Updated] = " + dict["C"]);
    }
}

ผลลัพธ์

Value associated with key C = Appliances
Value associated with key C [Updated] = HDD

คำอธิบายเพิ่มเติม

  • ListDictionary[key] ใช้ได้ทั้ง get และ set ค่า (indexer)
  • Get: คืนค่าที่เกี่ยวกับคีย์, คืน null ถ้าคีย์ไม่มีอยู่ (ไม่โยน exception)
  • Set: ถ้าคีย์มีอยู่ -> อัปเดตค่า, ถ้าไม่มี -> เพิ่มรายการใหม่ (upsert behavior)
  • ต่างจาก Add(key, value) ที่โยน ArgumentException ถ้าคีย์ซ้ำ
  • ListDictionary ใช้ linked list - เหมาะสำหรับข้อมูลน้อย (< 10 รายการ)
  • Key เป็น case-sensitive (แยกตัวพิมพ์ใหญ่เล็ก) ต่างจาก HybridDictionary/StringDictionary
  • เวลา complexity: O(n) - ต้องเดิน linked list หาคีย์ (linear search)
  • เป็น legacy class - แนะนำใช้ Dictionary<TKey, TValue> แทน (O(1) average)