Given a String
that is a Key
contained in Dictionary<String, List<String>>
, how do I retrieve the KeyValuePair<String, List<String>>
that corresponds to that Key
?
The problem with other answers using FirstOrDefault
is that it will sequentially search the entire dictionary until it finds a match, and you lose the benefit of having a hashed lookup. It seems more sensible if you really need a KeyValuePair
to just build one, like this:
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]);
}
}
(with credit to David Pine for the original code in his answer).
Here's a fiddle for that: https://dotnetfiddle.net/Zg8x7s
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With