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

คลาส Pair ใน C# (KeyValuePair)


ภาพรวม

KeyValuePair<TKey, TValue> (มักเรียกว่า Pair) ใช้เก็บ คู่คีย์-ค่า เดียว ใช้ภายใน Dictionary<TKey, TValue> และสามารถใช้แยกต่างหากได้

รูปแบบการใช้งาน

var list = new List>();
list.Add(new KeyValuePair("Laptop", 1));
list.Add(new KeyValuePair("Desktop", 2));

ตัวอย่างโค้ดเต็ม

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        var myList = new List>();
        myList.Add(new KeyValuePair("Laptop", 1));
        myList.Add(new KeyValuePair("Desktop System", 2));
        myList.Add(new KeyValuePair("Tablet", 3));
        myList.Add(new KeyValuePair("Mobile", 4));
        myList.Add(new KeyValuePair("E-Book Reader", 5));
        myList.Add(new KeyValuePair("LED", 6));
        foreach (var val in myList) Console.WriteLine(val);
    }
}

ผลลัพธ์

[Laptop, 1]
[Desktop System, 2]
[Tablet, 3]
[Mobile, 4]
[E-Book Reader, 5]
[LED, 6]

ข้อมูลเพิ่มเติม

  • Immutable struct - ไม่สามารถเปลี่ยน Key/Value หลังสร้างได้
  • เข้าถึง: pair.Key, pair.Value
  • Deconstruct (C# 7+): var (key, value) = pair;
  • C# 7+ Tuple: (string Key, int Value) ใช้แทนได้ บางกรณีสะดวกกว่า
  • Dictionary ใช้ KeyValuePair ภายใน - foreach (var kvp in dict)