获取给定 Key 的 KeyValuePair
Get KeyValuePair given Key
给定 String
是 Dictionary<String, List<String>>
中包含的 Key
,我如何检索对应于 Key
的 KeyValuePair<String, List<String>>
?
通常您需要与键关联的值,例如:
Dictionary<String, List<String>> dictionary = GetDictionary();
var value = dictionary["key"];
但是你可以使用Linq
得到整个KeyValuePair
:
var dictionary = new Dictionary<string, List<string>>
{
["key1"] = new List<string> { "1" },
["key2"] = new List<string> { "2" },
["key3"] = new List<string> { "3" },
};
var keyValuePair = dictionary.FirstOrDefault(kvp => kvp.Key == "key2");
Console.WriteLine(keyValuePair?.Value[0]); // Prints "2"
这里是.NET Fiddle.
使用 FirstOrDefault
的其他答案的问题是它会按顺序搜索整个字典,直到找到匹配项,这样您就失去了散列查找的好处。如果你真的需要一个 KeyValuePair
来构建一个,这似乎更明智,就像这样:
public class Program
{
public static void Main(string[] args)
{
var dictionary = new Dictionary<string, List<string>>
{
["key1"] = new List<string> { "1" },
["key2"] = new List<string> { "2" },
["key3"] = new List<string> { "3" },
};
var key = "key2";
var keyValuePair = new KeyValuePair<string, List<string>>(key, dictionary[key]);
Console.WriteLine(keyValuePair.Value[0]);
}
}
(感谢 David Pine 回答中的原始代码)。
这是一个 fiddle:https://dotnetfiddle.net/Zg8x7s
给定 String
是 Dictionary<String, List<String>>
中包含的 Key
,我如何检索对应于 Key
的 KeyValuePair<String, List<String>>
?
通常您需要与键关联的值,例如:
Dictionary<String, List<String>> dictionary = GetDictionary();
var value = dictionary["key"];
但是你可以使用Linq
得到整个KeyValuePair
:
var dictionary = new Dictionary<string, List<string>>
{
["key1"] = new List<string> { "1" },
["key2"] = new List<string> { "2" },
["key3"] = new List<string> { "3" },
};
var keyValuePair = dictionary.FirstOrDefault(kvp => kvp.Key == "key2");
Console.WriteLine(keyValuePair?.Value[0]); // Prints "2"
这里是.NET Fiddle.
使用 FirstOrDefault
的其他答案的问题是它会按顺序搜索整个字典,直到找到匹配项,这样您就失去了散列查找的好处。如果你真的需要一个 KeyValuePair
来构建一个,这似乎更明智,就像这样:
public class Program
{
public static void Main(string[] args)
{
var dictionary = new Dictionary<string, List<string>>
{
["key1"] = new List<string> { "1" },
["key2"] = new List<string> { "2" },
["key3"] = new List<string> { "3" },
};
var key = "key2";
var keyValuePair = new KeyValuePair<string, List<string>>(key, dictionary[key]);
Console.WriteLine(keyValuePair.Value[0]);
}
}
(感谢 David Pine 回答中的原始代码)。
这是一个 fiddle:https://dotnetfiddle.net/Zg8x7s