简体   繁体   English

C#字典递归

[英]C# Dictionary recursion

I'm searching for a construct in c# where Dictionaries contain Dictionaries to count n .我正在 c# 中搜索一个构造,其中 Dictionaries 包含 Dictionaries 来计算n I want to put a list of Dictionaries into and it builds some kind of index.我想将字典列表放入其中并构建某种索引。

I want to call it like dic[key][key2][key3] where the value is object or a Dictionary or a Dictionary containing more Dictionaries.我想称它为dic[key][key2][key3] ,其中值是对象或字典或包含更多字典的字典。

I think elastic can provide something like that but our solution is a standalone client application.我认为 elastic 可以提供类似的东西,但我们的解决方案是一个独立的客户端应用程序。

Dictionaries can be nested like this:字典可以这样嵌套:

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

To initialise a nested dictionary:初始化嵌套字典:

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

You then index into the dictionary like this:然后,您可以像这样对字典进行索引:

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

EDIT: to have an arbitrary depth, you need to create your own type that has built-in nesting, eg,编辑:要具有任意深度,您需要创建自己的具有内置嵌套的类型,例如,

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

Normally I would define Children as a List, but you want dictionaries.通常我会将 Children 定义为 List,但您需要字典。

Sample usage:示例用法:

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

This can go as deep as you like--just stick another Dictionary into the Children property of a leaf node.这可以深入到您喜欢的程度——只需将另一个字典粘贴到叶节点的 Children 属性中即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM