我有一个清单MyObject1
:
public class MyObject1
{
public int Id {get; set;}
public int ParentId {get; set;}
}
List<MyObject1> list = new List<MyObject1>();
我需要使用以下方法构建树MyObject2
:
public class MyObject2
{
public int Id {get; set;}
public int ParentId {get; set;}
// Here should be all child objects, that have .ParentId property is
// equal to .Id property of current node
public List<MyObject2> Children = new List<MyObject2>();
}
最快的方法是什么?也许我应该在构建之前或之前对我list
的排序?Id
ParentId
ETA 我的尝试:
MyObject2 root = MyObject2(1, 0); // in constructor id, parentId
foreach (MyObject1 obj1 in list)
{
// Traversing all tree within root (let's say myTree),
//if myTree.ParentId = obj1.Id then:
myTree.Children.Add(new MyObject2(obj1.Id, obj1.ParentId));
}
问题是如果.Id
树中还没有任何对象呢?这是最好的方法吗?