【问题标题】:How To Create a Dictionary Tree in C#如何在 C# 中创建字典树
【发布时间】:2016-06-07 04:03:43
【问题描述】:

我有以下代码:

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

它在允许我拥有 {KType, VType} 的嵌套“对”树方面非常有效。但是,因为我有一个列表而不是字典,所以我没有办法强制密钥是唯一的。 如何构建字典树或字典链或等价物?我想将“儿童”的基础类型更改为字典,但这需要一个 KeyValuePair,它只需要 2 个项目,一个键和一个值,孙辈就没有空间了。

【问题讨论】:

  • 您需要定义为 Dictionary 的 FOO 类中的字典
  • 为根还是子?

标签: c# dictionary tree


【解决方案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
                    }
                }
            }
        };
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-10
    • 2023-04-03
    • 2010-09-21
    相关资源
    最近更新 更多