如何在C#中创建字典树

时间:2016-06-07 04:03:44

标签: c# dictionary tree

我有以下代码:

if { [info commands wm] != {} } {wm withdraw .}

它允许我拥有{KType,VType}的嵌套“对”树,它的工作非常精彩。但是,因为我有一个List而不是一个Dictionary,所以我没有办法强制键是唯一的。 如何构建一个字典或字典链或等价字符?我想将“Children”的基础类型更改为字典,但这需要一个KeyValuePair,它只需要2个项目,一把钥匙和一个价值,孙子孙女没有空间。

1 个答案:

答案 0 :(得分:1)

As mentioned by @jdweng,字典可以将键映射到foos:

class Foo<KType, VType>
{
    public VType Value;
    public Dictionary<KType, Foo<KType, VType>> Children;
}

class Test
{
    public Test()
    {
        var root = new Foo<int, string>
        {
            Value = "root",
            Children = new Dictionary<int, Foo<int, string>>
            {
                {
                    1,
                    new Foo<int, string>
                    {
                        Value = "a",
                        Children = new Dictionary<int, Foo<int, string>>
                        {
                            {1, new Foo<int, string> {Value = "a", Children = null}},
                            {2, new Foo<int, string> {Value = "b", Children = null}}
                        }
                    }
                },
                {
                    2,
                    new Foo<int, string>
                    {
                        Value = "b",
                        Children = null
                    }
                }
            }
        };
    }
}