如何在 C# 中创建字典树
How To Create a Dictionary Tree in C#
我有以下代码:
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} 的嵌套 "pairs" 树,效果非常好。但是,因为我有一个列表而不是一个字典,所以我没有办法强制键是唯一的。 如何构建树或字典链或等效项?我想将 "Children" 的基础类型更改为字典,但这需要一个 KeyValuePair,它只需要 2 个项目,一个键和一个值,孙子们就没有空间了。
,字典可以将键映射到 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
}
}
}
};
}
}
我有以下代码:
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} 的嵌套 "pairs" 树,效果非常好。但是,因为我有一个列表而不是一个字典,所以我没有办法强制键是唯一的。 如何构建树或字典链或等效项?我想将 "Children" 的基础类型更改为字典,但这需要一个 KeyValuePair,它只需要 2 个项目,一个键和一个值,孙子们就没有空间了。
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
}
}
}
};
}
}