List<KeyValuePair 如何查找指定key的value
时间: 2024-04-14 18:28:18 浏览: 17
您可以使用 `List<KeyValuePair>` 的 `Find` 方法来查找指定 `key` 的 `value`。以下是一个示例:
```csharp
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// 创建 List<KeyValuePair> 示例
List<KeyValuePair<string, int>> keyValuePairs = new List<KeyValuePair<string, int>>
{
new KeyValuePair<string, int>("key1", 1),
new KeyValuePair<string, int>("key2", 2),
new KeyValuePair<string, int>("key3", 3)
};
// 要查找的 key
string keyToFind = "key2";
// 使用 Find 方法查找指定 key 的 value
KeyValuePair<string, int> foundPair = keyValuePairs.Find(pair => pair.Key == keyToFind);
if (foundPair.Key != null)
{
Console.WriteLine($"找到 key: {foundPair.Key},对应的 value: {foundPair.Value}");
}
else
{
Console.WriteLine($"未找到指定的 key: {keyToFind}");
}
}
}
```
在上述示例中,我们创建了一个 `List<KeyValuePair<string, int>>`,其中包含几个键值对。然后,我们使用 `Find` 方法来查找指定的 `key`,并打印相应的 `value`。请注意,`Find` 方法接受一个 `Predicate` 来定义查找条件。在这个例子中,我们使用了一个 lambda 表达式来匹配键与指定的 `keyToFind`。
希望这可以帮助到您!如果有任何进一步的问题,请随时提问。