2014-07-01 40 views
0

我正在尋找一種方式來表示,有一個家長,一個孩子,和一個孫子對象的對象。我不想用:如何處理父母/孩子/ GrandChild關係?

IEnumerable<IEnumerable<IEnumerable<Node>>> 

如果它是完全有可能的。

每個節點都是一樣的:

public class Node 
{ 
    public string Text { get; set; } 
    public string Value { get; set; } 
    public string Title { get; set; } 
} 

我要代表樹狀結構,其中有三個級別的數據。防爆

ParentNode 
    ChildNode 

ParentNode 
    ChildNode 
     GrandChildNode 
     GrandChildNode 

我試圖這樣做,因爲一般/乾淨越好,這樣我可以重複使用從數據庫獲取該信息的服務。

任何建議嗎?

+0

爲什麼你不希望使用嵌套的IEnumerable? – gunr2171

+1

添加'Children'屬性'Node'是一個IEnumerable的''和'Parent'屬性,它的類型是Node'的'。 –

+0

@ gunr2171這是非常令人費解有多個嵌套列表及其難以閱讀,並按照最次 – Robert

回答

5

您可以修改您的類,以適應像層次樹。

public class Node 
{ 
    public string Text { get; set; } 
    public string Value { get; set; } 
    public string Title { get; set; } 

    public Node Parent { get; private set; } 
    public ICollection<Node> Children { get; private set; } 

    public IEnumerable<Node> Ancestors() { 
     Node current = this.Parent; 
     while (current != null) { 
      yield return current; 
      current = current.Parent;     
     } 
    } 

    public IEnumerable<Node> Descendants() { 
     foreach (Node c in this.Children) { 
      yield return c; 
      foreach (Node d in c.Descendants()) 
       yield return d; 
     } 
    } 

    // Root node constructor 
    public Node() { 
     this.Children = new List<Node>();  
    } 

    // Child node constructor 
    public Node(Node parent) : this() { 
     this.Parent = parent; 
     parent.Children.Add(this); 
    } 
} 

然後,您可以使用它,像這樣:

Node gramps = new Node() { Title = "Grandparent" }; 
Node dad = new Node(gramps) { Title = "Parent" }; 
Node son = new Node(dad) { Title = "Child" };