The KeyValuePair class stores a pair of values in a single list with C#.
Set KeyValuePair and add elements −
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));Here is the code to learn how to work with KeyValuePair and display the keys and values −
Example
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);
}
}
}