Search code examples
c#jsondictionaryjson.nettrygetvalue

Is it Possible to use TryGetValue on deep nested dictionary?


I want to access a certain property on a dictionary safelay with the TryGetValue-method.

For example an entry i would directly access like this:

jsonObject[prop1][prop2][0][prop3]

Is there any convenient way to do so?


Solution

  • Here's one idea (untested). It does assume a nested IDictionary at least as deep as the number of keys specified, and works in object (you could of course do things to make this a generic):

    bool TryGetNestedValue (this IDictionary dict, out object value, 
        params object[] keys)
    {
        for(int i = 0; i < keys.Length; i++)
        {
            var key = keys[i];
    
            if (!dict.Contains(key))
            {
                value = null;
                return false;
            }
    
            if (i == keys.Length - 1)
            {
                value = dict[key];
                return true;
            }
    
            dict = dict[key];
        }
    
        throw new ArgumentException("keys");
    }