Get value from a dictionary contained in a dictionary I have an API that returns a dictionary of dictionaries.

I currently have this code to access the value of the dictionary, but it looks like a code smell. Is there a better way to structure this?

// Dictionary&lt;string, Dictionary&lt;DateTime, string&gt;&gt; CountryCode();

var response = api.CountryCode();

string GB2001;
if (response.ContainsKey("GB") &amp;&amp; response["GB"].ContainsKey(new DateTime(2001, 04, 01)))
{
    GB2001 = response["GB"][new DateTime(2001, 04, 01)];

    // Use the result of GB2001 here
}
The 'problem' with this approach is that you perform a lookup twice for each key.


ContainsKey
indexer lookup [..]


code


if (response.ContainsKey("GB") &amp;&amp; response["GB"].ContainsKey(new DateTime(2001, 04, 01)))
{
    GB2001 = response["GB"][new DateTime(2001, 04, 01)];
}



Use TryGetValue to combine lookup and indexer.

string GB2001;
if (response.TryGetValue("GB", out var country))
{
    country?.TryGetValue(new DateTime(2001, 04, 01), out GB2001);
}