【发布时间】:2016-11-20 15:23:34
【问题描述】:
来自here 我问自己是否有更简单的方法来对类进行排序
public class ParentChild
{
int ID { get; set; }
int ParentID { get; set; }
public ParentChild(int id, int pid)
{
ID = id;
ParentID = pid;
}
}
取决于它的父母关系。
例如
List<ParentChild> pcItems = new List<ParentChild>()
{
new ParentChild(1,0), // 0 is the default value in case of no parent
new ParentChild(2,1),
new ParentChild(3,2),
new ParentChild(4,2),
new ParentChild(5,1),
new ParentChild(6,4),
new ParentChild(7,1),
new ParentChild(8,6),
new ParentChild(9,3)
};
因此,项目应具有以下排序顺序:首先按子关系排序,然后按 ID。
1 // root
+-2
| +-3
| | +-9 // is the child of 3
| | 4 //is the 2nd child of 2 and has the higher ID conmpared to 3
| | +-6
| | +-8
| 5
7
本题不打算按层次顺序显示数据。与我在链接帖子中的答案相比,这只是一个更简单/非递归/linq OrderBy / Sort。
【问题讨论】:
-
“我在链接的帖子中有一个工作方法,所以不需要努力” -- 是的,有。每个 Stack Overflow 问题都需要独立存在,因此如果相关问题被删除,问题仍然有意义。