Hi..Rajesh
KeyValue Pair Stores two values together. It is a single generic structure in c# progamming language.
The KeyValuePair type in System.Collections.Generic is simple and always available. It is used internally in Dictionary and other collections.
Example
List type
First this example shows how you can use KeyValuePair in a List, which is also in System.Collections.Generic. This is useful for storing pairs of values in a single List.
Alternatively: You could use two separate Lists, but that can complicate matters.
Program that uses KeyValuePair [C#]
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Shows a List of KeyValuePairs.
var list = new List<KeyValuePair<string, int>>();
list.Add(new KeyValuePair<string, int>("Cat", 1));
list.Add(new KeyValuePair<string, int>("Dog", 2));
list.Add(new KeyValuePair<string, int>("Rabbit", 4));
foreach (var element in list)
{
Console.WriteLine(element);
}
}
}
Output
[Cat, 1]
[Dog, 2]
[Rabbit, 4]
This Example shows how you can initialize a new List of type KeyValuePair. Inside the brackets in the KeyValuePair, there are two types separated by a comma. This example shows KeyValuePairs of one string and one int each.
KeyValue Pair and Name Value Pair Both are Different...
Thanks & Regards
Sravya
Rajeshk, if this helps please login to Mark As Answer. | Alert Moderator