2012-08-05 115 views
0

考慮下面的類,用於構建一個樹層次結構的特定級別:獲取所有節點在樹上

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,我怎麼會從同級別的所有節點?節點名稱可以是任何東西。

+0

創建方法'Depth',對於每個節點返回其深度到根?然後LINQ用適當的查詢選擇根節點? – 2012-08-05 13:37:07

+2

你可以創建一個Level/Depth屬性,然後根據這個屬性查詢對象,或者創建一個基本的for循環,它遍歷你的樹項目到期望的級別,在這一點上它選擇這些對象 – timothyclifford 2012-08-05 13:39:44

回答

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; 
    } 
} 
+0

感謝BlackBear,給定我的樣本數據確實獲得了指定深度的所有節點。我確實注意到結果包含重複項,深度爲1,則返回兩個level1childA和兩個level1childB。此外,如果深度指定爲3(最底層並且節點沒有子節點(葉節點?)),則會在「foreach(this.Children中的簡單測試元素)」行上生成錯誤。 – 2012-08-05 14:52:45

+0

@JohnSmith:我在代碼中發現了一個錯字,現在就試試。至於錯誤我相信是因爲Children爲null而發生的,所以你應該在costructor中初始化它。 – BlackBear 2012-08-05 15:30:42

+0

非常感謝BlackBear。 – 2012-08-05 16:25:04