C# 字典递归

C# Dictionary recursion

我正在 c# 中搜索一个结构,其中字典包含要计数的字典 n。我想将字典列表放入其中并构建某种索引。

我想像 dic[key][key2][key3] 那样称呼它,其中值是对象或字典或包含更多字典的字典。

我认为 elastic 可以提供类似的东西,但我们的解决方案是一个独立的客户端应用程序。

字典可以这样嵌套:

        var dictionary = new Dictionary<string, Dictionary<string, int>>();

要初始化嵌套字典:

        var dictionary = new Dictionary<string, Dictionary<string, int>>
        {
            { "a1", new Dictionary<string, int> { { "b1a", 1 }, { "b1b", 2 } } },
            { "a2", new Dictionary<string, int> { { "b2a", 3 }, { "b2b", 4 } } }
        };

然后像这样在字典中建立索引:

        int x = dictionary["a1"]["b1a"];
        Assert.AreEqual(1, x);

编辑:要具有任意深度,您需要创建自己的具有内置嵌套的类型,例如,

    class Node
    {
        public int Value { get; set; }

        public Dictionary<string, Node> Children { get; set; }

        // The indexer indexes into the child dictionary.
        public Node this[string key] => Children[key];
    }

通常我会将 Children 定义为列表,但您需要字典。

示例用法:

        var node = new Node
        {
            Children = new Dictionary<string, Node>
            {
                { "a1", new Node
                    {
                        Children = new Dictionary<string, Node>
                        {
                            { "b1a", new Node { Value = 1 } },
                            { "b1b", new Node { Value = 2 } }
                        }
                    }
                },
                { "a2", new Node
                    {
                        Children = new Dictionary<string, Node>
                        {
                            { "b2a", new Node { Value = 3 } },
                            { "b2b", new Node { Value = 4 } }
                        }
                    }
                }
            }
        };

        int y = node["a1"]["b1a"].Value;
        Assert.AreEqual(1, y);

这可以深入到你喜欢的程度——只需将另一个字典插入叶节点的子节点 属性 即可。