【问题标题】:Is it Possible to use TryGetValue on deep nested dictionary?是否可以在深度嵌套字典上使用 TryGetValue?
【发布时间】:2013-03-21 13:11:05
【问题描述】:

我想使用 TryGetValue 方法访问字典保险箱上的某个属性。

例如,我会像这样直接访问的条目:

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

有什么方便的方法吗?

【问题讨论】:

  • 如果值不存在,你期望它做什么? jsonObject是什么类型的?

标签: c# json dictionary json.net trygetvalue


【解决方案1】:

这是一个想法(未经测试)。它确实假定嵌套的 IDictionary 至少与指定的键数一样深,并且在 object 中工作(您当然可以做一些事情使其成为通用的):

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");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-30
    • 2012-03-07
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多