คลาส KeyValuePair เก็บคู่ของค่าไว้ในรายการเดียวด้วย C#
ตั้งค่า KeyValuePair และเพิ่มองค์ประกอบ -
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)); นี่คือรหัสสำหรับเรียนรู้วิธีการทำงานกับ KeyValuePair และแสดงคีย์และค่าต่างๆ -
ตัวอย่าง
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);
}
}
}