C#字典递归

时间:2020-02-26 17:01:41

标签: c# dictionary recursion indexing self-contained

我正在c#中搜索一个结构,其中字典包含要计算maximum的字典。我想放入一个字典列表,它可以建立某种索引。

我想像n这样称呼它,其中值是object或Dictionary或包含更多Dictionary的Dictionary。

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

1 个答案:

答案 0 :(得分:1)

字典可以像这样嵌套:

        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];
    }

通常,我将“儿童”定义为“列表”,但是您需要字典。

样品用量:

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

它可以随心所欲-只需将另一个Dictionary插入叶节点的Children属性即可。