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

KeyValuePair ใน C#: การจัดเก็บคู่คีย์-ค่าในลิสต์

KeyValuePair<TKey, TValue> เป็นโครงสร้างข้อมูล (struct) ที่จัดเก็บคู่ของคีย์และค่าในหน่วยเดียว ใช้กันอย่างแพร่หลายใน Dictionary และเมื่อต้องการเก็บคู่ข้อมูลใน List โดยไม่ต้องการความสามารถในการค้นหาแบบ Dictionary

การประกาศและเพิ่มข้อมูล

var list = new List>();

list.Add(new KeyValuePair("Laptop", 20));
list.Add(new KeyValuePair("Desktop", 40));
list.Add(new KeyValuePair("Tablet", 60));

// หรือใช้ตัวสร้างแบบย่อ (C# 7+)
list.Add(KeyValuePair.Create("Phone", 80));

โค้ดตัวอย่างสมบูรณ์

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        var devices = new List>();
        
        // เพิ่มข้อมูล
        devices.Add(new KeyValuePair("Laptop", 20));
        devices.Add(new KeyValuePair("Desktop", 40));
        devices.Add(new KeyValuePair("Tablet", 60));
        devices.Add(KeyValuePair.Create("Phone", 80));
        devices.Add(KeyValuePair.Create("Watch", 15));
        
        Console.WriteLine("รายการอุปกรณ์:");
        foreach (var device in devices)
        {
            Console.WriteLine($"  {device.Key,-10} : {device.Value,3} หน่วย");
        }
        
        // การเข้าถึงคีย์และค่า
        Console.WriteLine($"\nอุปกรณ์ตัวแรก: {devices[0].Key} = {devices[0].Value}");
        
        // ค้นหา (ต้องวนลูป เพราะ List ไม่มีการค้นหาโดยคีย์)
        string search = "Tablet";
        var found = devices.Find(kvp => kvp.Key == search);
        if (!found.Equals(default(KeyValuePair)))
            Console.WriteLine($"พบ {search}: {found.Value} หน่วย");
        else
            Console.WriteLine($"ไม่พบ {search}");
    }
}

ผลลัพธ์

รายการอุปกรณ์:
  Laptop     :  20 หน่วย
  Desktop    :  40 หน่วย
  Tablet     :  60 หน่วย
  Phone      :  80 หน่วย
  Watch      :  15 หน่วย

อุปกรณ์ตัวแรก: Laptop = 20
พบ Tablet: 60 หน่วย

KeyValuePair vs Dictionary - เมื่อไหนควรใช้ตัวไหน?

ลักษณะKeyValuePair ใน ListDictionary
ค้นหาตามคีย์O(n) - ต้องวนลูปO(1) - เร็วมาก
อนุญาตคีย์ซ้ำได้ไม่ได้ (โยน Exception)
รักษาลำดับการเพิ่มได้ได้ (NET 6+)
หน่วยความจำน้อยกว่า (struct)มากกว่า (hash table)
เหมาะสำหรับข้อมูลเล็ก, ต้องการคีย์ซ้ำ, ต้องการลำดับข้อมูลเยอะ, ค้นหาบ่อย, คีย์ไม่ซ้ำ

การใช้งานร่วมกับ LINQ

using System.Linq;

// เรียงตามค่า
var sorted = devices.OrderByDescending(kvp => kvp.Value);

// กรอง
var expensive = devices.Where(kvp => kvp.Value > 30);

// แปลงเป็น Dictionary (ถ้าคีย์ไม่ซ้ำ)
var dict = devices.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

Deconstruction (C# 7+)

foreach (var (key, value) in devices)
{
    Console.WriteLine($"{key} = {value}");
}

// หรือ
foreach (var kvp in devices)
{
    var (key, value) = kvp; // deconstruct
    Console.WriteLine($"{key} = {value}");
}