Getting Items from Dictionary by key

SexyMF picture SexyMF · Sep 20, 2011 · Viewed 18.9k times · Source

I have this structure:

static Dictionary<int, Dictionary<int, string>> tasks = 
    new Dictionary<int, Dictionary<int, string>>();

it looks like that

[1]([8] => "str1")
[3]([8] => "str2")
[2]([6] => "str3")
[5]([6] => "str4")

I want to get from this list all of the [8] strings, meaning str1 + str2
The method should look like the following:

static List<string> getTasksByNum(int num){

}

How do I access it?

Answer

Ani picture Ani · Sep 20, 2011

With LINQ, you can do something like:

return tasks.Values
            .Where(dict => dict.ContainsKey(8))
            .Select(dict => dict[8])
            .ToList();      

While this is elegant, the TryGetValue pattern is normally preferable to the two lookup operations this uses (first trying ContainsKey and then using the indexer to get the value).

If that's an issue for you, you could do something like (with a suitable helper method):

return tasks.Values
            .Select(dict => dict.TryGetValueToTuple(8))
            .Where(tuple => tuple.Item1)
            .Select(tuple => tuple.Item2)
            .ToList();