as9876
as9876

Reputation: 956

How To Create a Dictionary Tree in C#

I have the following code:

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

It works beautifully in allowing me to have a tree of nested "pairs" of {KType, VType}. However, because I have a List and not a Dictionary, I don't have a way of enforcing that the keys will be unique. How can I construct a tree or chain of dictionaries or the equivalent? I'd like to change the underlying type of "Children" to a dictionary, but that takes a KeyValuePair, which takes only 2 items, a key and a value, and there'd be no room for the grandchildren.

Upvotes: 3

Views: 5168

Answers (1)

Adriano
Adriano

Reputation: 1723

As mentioned by @jdweng, the dictionary could map keys to 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
                    }
                }
            }
        };
    }
}

Upvotes: 3

Related Questions