考慮下面的類,用於構建一個樹層次結構的特定級別:獲取所有節點在樹上
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 };
因此,例如,使用節點level3childE,我怎麼會從同級別的所有節點?節點名稱可以是任何東西。
創建方法'Depth',對於每個節點返回其深度到根?然後LINQ用適當的查詢選擇根節點? – 2012-08-05 13:37:07
你可以創建一個Level/Depth屬性,然後根據這個屬性查詢對象,或者創建一個基本的for循環,它遍歷你的樹項目到期望的級別,在這一點上它選擇這些對象 – timothyclifford 2012-08-05 13:39:44