给定以下类,用于构建树层次结构:
public class simpletest
{
public simpletest Parent { get; set; }
public IList<simpletest> Children { get; set; }
public string Name { get; set; }
}
如何获取特定级别的所有对象列表?
以下是一些示例数据(希望其格式正确):
var root = new simpletest() { Name = "Root" };
var level1childA = new simpletest() { Name = "level1childA", Parent = root };
var level1childB = new simpletest() { Name = "level1childB", Parent = root };
var level2childA = new simpletest() { Name = "level2childA", Parent = level1childA };
var level2childB = new simpletest() { Name = "level2childB", Parent = level1childA };
var level2childC = new simpletest() { Name = "level2childC", Parent = level1childB };
var level2childD = new simpletest() { Name = "level3childD", Parent = level1childB };
var level3childA = new simpletest() { Name = "level3childA", Parent = level2childA };
var level3childB = new simpletest() { Name = "level3childB", Parent = level2childA };
var level3childC = new simpletest() { Name = "level3childC", Parent = level2childB };
var level3childD = new simpletest() { Name = "level3childD", Parent = level2childB };
var level3childE = new simpletest() { Name = "level3childE", Parent = level2childC };
var level3childF = new simpletest() { Name = "level3childF", Parent = level2childC };
var level3childG = new simpletest() { Name = "level3childG", Parent = level3childD };
var level3childH = new simpletest() { Name = "level3childH", Parent = level3childD };
level2childA.Children = new List<simpletest> { level3childA, level3childB };
level2childB.Children = new List<simpletest> { level3childC, level3childD };
level2childC.Children = new List<simpletest> { level3childE, level3childF };
level2childD.Children = new List<simpletest> { level3childG, level3childH };
level1childA.Children = new List<simpletest> { level2childA, level2childB };
level1childB.Children = new List<simpletest> { level2childC, level2childD };
例如,使用node level3childE,我如何从同一级别获取所有节点?节点名称可以是任何名称。
答案 0 :(得分:1)
这是一个(未经测试的)递归方法,作为simpletest的成员函数实现:
IEnumerable<simpletest> ElementsAtDepth(int depth) {
if(depth > 0) {
foreach(simpletest child in this.Children)
foreach(simpletest element in child.ElementsAtDepth(depth - 1))
yield return element;
}
else {
foreach(simpletest element in this.Children)
yield return element;
}
}
答案 1 :(得分:0)
BlackBear的解决方案返回下一级别,无法返回可能对绑定有用的root / initial节点。 下面的代码将为您提供所请求级别的节点。 另请注意,深度是相对于初始节点而不是实际树。
'/^[a-z][a-z ][\x{0410}-\x{042F}]*$/i'
'/^[a-z][a-z ][А-Яа-яЁё]*$/i'
'/^[a-z][a-z ][\p{Cyrillic}]*$/i'