Pseudo Sudo
Pseudo Sudo

Reputation: 1412

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?

Upvotes: 7

Views: 14049

Answers (2)

Richard Irons
Richard Irons

Reputation: 1473

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

Upvotes: 6

David Pine
David Pine

Reputation: 24525

Usually you want the value associated with the key, for example:

Dictionary<String, List<String>> dictionary = GetDictionary();
var value = dictionary["key"];

But you can use Linq to get the entire 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"

Here is a .NET Fiddle.

Upvotes: 0

Related Questions