如何在C#中创建字典树

3
我有如下代码:
class Foo<KType, VType>
{
    public KType Key;
    public VType Value;
    public List<Foo<KType, VType>> Children;
}

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

它能够很好地让我拥有一个嵌套的“键值对”树形结构,但是由于我使用的是List而不是Dictionary,我没有办法强制要求键是唯一的。我应该如何构建字典树或链表等等?我想将“Children”的基础类型更改为字典,但这需要一个KeyValuePair,它只包含两个项,即键和值,而没有空间给孙子节点。

2
你需要在类FOO中定义一个字典,其定义为Dictionary<KType, Foo>。 - jdweng
是为根节点还是子节点? - as9876
1个回答

3

正如 @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
                    }
                }
            }
        };
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接