Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get KeyValuePair given Key

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?

like image 209
Pseudo Sudo Avatar asked Aug 24 '16 12:08

Pseudo Sudo


1 Answers

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

like image 65
Richard Irons Avatar answered Oct 13 '22 00:10

Richard Irons