How is the KeyValuePair used in C#?
KeyValuePair in C# is a generic structure used for storing key-value pairs. It associates a key with a value, allowing for simultaneous access to both. KeyValuePair is commonly used to store data in dictionaries or collections.
Here is an example demonstrating how to use KeyValuePair:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// 创建一个KeyValuePair
KeyValuePair<int, string> pair = new KeyValuePair<int, string>(1, "apple");
// 访问键和值
Console.WriteLine($"Key: {pair.Key}, Value: {pair.Value}");
// 在字典中使用KeyValuePair
Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(pair.Key, pair.Value);
foreach (KeyValuePair<int, string> kvp in dict)
{
Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");
}
}
}
In the example above, we start by creating a KeyValuePair object and then accessing its key and value. Next, we add the KeyValuePair object to a dictionary and iterate through all KeyValuePairs in the dictionary using a foreach loop. KeyValuePair offers a convenient way to handle key-value pair data.
More tutorials
What is the method for traversing a dictionary in C#?(Opens in a new browser tab)
initializing and assigning values to a dictionary in C#(Opens in a new browser tab)
How do you call AutoResetEvent in C#?(Opens in a new browser tab)
How to add elements to a C# dictionary(Opens in a new browser tab)
How to retrieve a value from a C# dictionary using a key?(Opens in a new browser tab)