从c#中的对象列表中创建树结构

时间:2016-04-01 07:25:07

标签: c#

我有一个名为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 });

现在我想将此详细信息列表转换为树结构。

1 个答案:

答案 0 :(得分: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);