来自here我问自己是否有更简单的方法来排序类
public class ParentChild
{
int ID { get; set; }
int ParentID { get; set; }
public ParentChild(int id, int pid)
{
ID = id;
ParentID = pid;
}
}
取决于它的父母关系。
e.g。
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)
};
因此,Items应具有以下排序顺序:首先按子关系排序,然后按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
。
答案 0 :(得分:2)
在ParentChild
中修复构造函数后,您会发现这有效:
var lookup = pcItems.ToLookup(x => x.ParentID, x => x.ID);
Func<int, int, IEnumerable<string>> build = null;
build = (pid, level) =>
lookup[pid]
.SelectMany(id =>
new [] { "".PadLeft(level * 4) + id.ToString() }
.Concat(build(id, level + 1)));
IEnumerable<string> results = build(0, 0);
这给你这个:
它是递归的,但至少它是三行代码。 ; - )
获得一个排序结果:
var lookup = pcItems.ToLookup(x => x.ParentID, x => x.ID);
Func<int, int, IEnumerable<ParentChild>> build = null;
build = (pid, level) => lookup[pid]
.SelectMany(id => new[] { pcItems.Single(x => x.ID == id) }
.Concat(build(id, level + 1)));
IEnumerable<ParentChild> results = build(0, 0);
稍微清洁的版本:
var lookup = pcItems.ToLookup(x => x.ParentID);
Func<int, int, IEnumerable<ParentChild>> build = null;
build = (pid, level) =>
lookup[pid].SelectMany(pc => new[] { pc }.Concat(build(pc.ID, level + 1)));
IEnumerable<ParentChild> results = build(0, 0);