我有这样的数据库表:
ID Name ParentID isActive
1 ABC NULL true
2 DEF 1 true
3 GHI 1 true
4 JKL NULL true
5 MNO 4 true
6 PRS NULL true
7 TUV NULL true
8 WX 1 true
9 YZ 4 true
10 abc 7 true
我将其列入清单:
var projectList = connection.Where(d=>d.Active);
当我将此表添加到列表中时,我想按父ID对它们进行排序。因此,排序列表应如下所示:(每行替换下面的父行)。
1是2,3和8
4是5和9的父母
1|ABC
2|DEF
3|GHI
**4|WX**
5|JKL
6|MNO
**7|YZ**
8|PRS
9|TUV
**10|abc**
如何对此列表进行排序?
答案 0 :(得分:0)
您必须通过区分父元素和子元素来加入结果。我希望它有所帮助。
static void Main(string[] args)
{
var connection = new List<User>()
{
new User(1, "ABC", null, true),
new User(2, "DEF", 1, true),
new User(3, "GHI", 1, true),
new User(4, "JKL", null, true),
new User(5, "MNO", 4, true),
new User(6, "PRS", null, true),
new User(7, "TUV", null, true),
new User(8, "WX", 1, true),
new User(9, "YZ", 4, true),
new User(10, "abc", 7, true)
};
var filtered = connection.Where(x => x.Active).OrderBy(z => z.ParentID);
var result = filtered.Where(p => p.ParentID == null).GroupJoin(filtered, parent => parent.ID,
child => child.ParentID,
(parent, child) => new {Child = child, Parent = parent})
.Aggregate(new List<User>(), (outList, tempObj) =>
{
outList.Add(tempObj.Parent);
outList.AddRange(tempObj.Child);
return outList;
});
foreach (var item in result)
{
Console.WriteLine($"{item.ID} | {item.Name} | {item.ParentID}");
}
}
它产生以下输出:
1 | ABC |
2 | DEF | 1
3 | GHI | 1
8 | WX | 1
4 | JKL |
5 | MNO | 4
9 | YZ | 4
6 | PRS |
7 | TUV |
10 | abc | 7