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

Lớp Pair (KeyValuePair) trong C#

KeyValuePair<TKey, TValue> là struct đại diện cho một cặp khóa/giá trị. Thường dùng trong Dictionary hoặc lưu trữ cặp dữ liệu đơn giản.

Ví dụ: List của KeyValuePair

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);
    }
}

Kết quả

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

Lưu ý: KeyValuePair là struct (value type), không thể null. Từ C# 7.0, dùng tuple (string, int) ngắn gọn hơn.