Lớp KeyValuePair lưu trữ một cặp giá trị trong một danh sách duy nhất với C #.
Đặt KeyValuePair và thêm các phần tử -
var myList = new List<KeyValuePair<string, int>>();
// adding elements
myList.Add(new KeyValuePair<string, int>("Laptop", 20));
myList.Add(new KeyValuePair<string, int>("Desktop", 40));
myList.Add(new KeyValuePair<string, int>("Tablet", 60)); Đây là mã để tìm hiểu cách làm việc với KeyValuePair và hiển thị các khóa và giá trị -
Ví dụ
Using System;
using System.Collections.Generic;
class Program {
static void Main() {
var myList = new List<KeyValuePair<string, int>>();
// adding elements
myList.Add(new KeyValuePair<string, int>("Laptop", 20));
myList.Add(new KeyValuePair<string, int>("Desktop", 40));
myList.Add(new KeyValuePair<string, int>("Tablet", 60));
foreach (var val in myList) {
Console.WriteLine(val);
}
}
}