How to use KeyValuePair in C#
In C#, KeyValuePair
KeyValuePair
- Iterate through a dictionary in a loop: You can use KeyValuePair
to iterate through the key-value pairs of a dictionary (Dictionary ) in a loop. For example:
Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("apple", 1);
dict.Add("orange", 2);
foreach (KeyValuePair<string, int> kvp in dict)
{
Console.WriteLine("Key: " + kvp.Key + ", Value: " + kvp.Value);
}
Output result:
Key: apple, Value: 1
Key: orange, Value: 2
- Passing or returning key-value pairs as method parameters or return values can be done using KeyValuePair
. For example:
public KeyValuePair<string, int> GetMaxValue(Dictionary<string, int> dict)
{
KeyValuePair<string, int> maxKvp = new KeyValuePair<string, int>(null, int.MinValue);
foreach (KeyValuePair<string, int> kvp in dict)
{
if (kvp.Value > maxKvp.Value)
{
maxKvp = kvp;
}
}
return maxKvp;
}
- In LINQ queries, you can use KeyValuePair
to group or sort results. For example:
var dict = new Dictionary<string, int>()
{
{ "apple", 1 },
{ "orange", 2 },
{ "banana", 3 },
{ "grape", 4 }
};
var sortedDict = dict.OrderBy(kvp => kvp.Value);
foreach (KeyValuePair<string, int> kvp in sortedDict)
{
Console.WriteLine("Key: " + kvp.Key + ", Value: " + kvp.Value);
}
Output result:
Key: apple, Value: 1
Key: orange, Value: 2
Key: banana, Value: 3
Key: grape, Value: 4
In conclusion, KeyValuePair