Pse*_*udo 2 c# dictionary key-value
给定一个String是一个Key包含在Dictionary<String, List<String>>,我怎么检索KeyValuePair<String, List<String>>对应于该Key?
使用其他答案的问题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]);
}
}
Run Code Online (Sandbox Code Playgroud)
(在他的回答中将David Pine的原始代码归功于David Pine).
这是一个小提琴:https://dotnetfiddle.net/Zg8x7s