C# KeyValuePair

KeyValuePair is a key and a value combination.

using System.Collections.Generic;
KeyValuePair<int, int> kvp = new KeyValuePair<int, int>(2, 3);
kvp.Key; //2
kvp.Value; //3

KeyValuePair can be used as an element of a collection.
using System.Collections.Generic;
KeyValuePair<int, int> kvp = new KeyValuePair<int, int>(2, 3);
KeyValuePair<int, int> kvp2 = new KeyValuePair<int, int>(3, 9);
KeyValuePair<int, int> kvp3 = new KeyValuePair<int, int>(4, 21);
List<KeyValuePair<int, int>> lst = new List<KeyValuePair<int, int>> {kvp,kvp2,kvp3};

KeyValuePair can be use to loop through a dictionary:
using System.Collections.Generic;
Dictionary<string, int> d = new Dictionary<string, int> {
{"Jacobs",28},{"Mary",26}
};
foreach (KeyValuePair<string, int> p in d)
{
string name = p.Key;
int age = p.Value;
}



endmemo.com © 2024  | Terms of Use | Privacy | Home