2016-04-01 42 views
1

我有一個叫Detail類下面給出:製作樹結構

public class Detail 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public System.Nullable<int> ParentID { get; set; } 
} 

我做詳細的列表,下面給出:

 List<Detail> Details= new List<Detail>(); 

     Details.Add(new Detail { Id = 1, Name = "James", ParentID =null }); 
     Details.Add(new Detail { Id = 2, Name = "David", ParentID = 1 }); 
     Details.Add(new Detail { Id = 3, Name = "Richard", ParentID = 2 }); 
     Details.Add(new Detail { Id = 4, Name = "John", ParentID = 3 }); 
     Details.Add(new Detail { Id = 5, Name = "Robert", ParentID = 3 }); 
     Details.Add(new Detail { Id = 6, Name = "Paul", ParentID = 3 }); 
     Details.Add(new Detail { Id = 7, Name = "Kevin", ParentID = 2 }); 
     Details.Add(new Detail { Id = 8, Name = "Jason", ParentID = 7 }); 
     Details.Add(new Detail { Id = 9, Name = "Mark", ParentID = 7 }); 
     Details.Add(new Detail { Id = 10, Name = "Thomas", ParentID = 9 }); 
     Details.Add(new Detail { Id = 11, Name = "Donald", ParentID = 9 }); 

現在我要將這個Detail列表轉換成樹結構。

+0

請認真e對樹結構更具體,你如何想象節點被鏈接在一起?通過這個我的意思是,什麼標準將決定哪個節點與哪個節點鏈接? –

+0

@Remuze我編輯它。請再檢查一次。它只是一個細節 – devendra

+0

@Remuze ParentID將確定父節點。多數民衆贊成他們將如何鏈接在一起 – devendra

回答

3

你可以嘗試以下

添加一個新類來抱樹對象

public class TreeNode 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 

    public TreeNode Parent { get; set; } 
    public List<TreeNode> Children{ get; set; } 
} 

然後添加一個遞歸方法來構建樹

private static List<TreeNode> FillRecursive(List<Detail> flatObjects, int? parentId=null) 
{ 
    return flatObjects.Where(x => x.ParentID.Equals(parentId)).Select(item => new TreeNode 
    { 
    Name = item.Name, 
    Id = item.Id, 
    Children = FillRecursive(flatObjects, item.Id) 
    }).ToList(); 
} 

然後調用它,你需要它

var tree = FillRecursive(Details,null); 
+0

我覺得'FillRecursive'沒有設置'TreeNode.Parent',我會說在TreeNode中有'Parent'或'Children'屬性就足夠了 另外'FillRecursive'不會在無效輸入上終止,例如' {id = 1,ParentId = 2},{id = 2,ParentId = 1}' – ironstone13

+0

@ ironstone13有沒有更好的選擇? – devendra

+0

@devendra - 這取決於您是否需要對父節點的引用(您將如何遍歷樹),以及您是否期望輸入列表中的數據不一致 – ironstone13