我有一个具有以下基本结构的对象列表:
class Person
{
public int ID {get; set;}
public bool ShowChildren {get; set;}
public int ParentID {get; set;}
// ...many other properties...
}
我需要返回按其ID排序的Person父类列表。如果启用了ShowChildren标志,则还要返回其父级下的子级,按其ID排序。
这只是一个层次,即孩子不会有孩子。
我可以写一个linq语句来给我所有的父母,但是当我启用父标志时,我仍然坚持如何包含已排序的子项。
var People = PersonList
.Where(x => x.ParentID == 0)
.Orderby(x => x.ID)
.ToList();
答案 0 :(得分:4)
很抱歉,除非明确要求,否则你只想归还父母(感谢@Rawling!),foreach
循环也很好。
var people = new List<Person>();
PersonList.Sort((a, b) => a.ID - b.ID);
foreach(Person p in PersonList) {
if(p.ParentID == 0) { // Or whatever value you use to represent it
people.Add(p);
if(p.ShowChildren) {
people.AddRange(PersonList.Where(c => c.ParentID == p.ID));
}
}
}
答案 1 :(得分:1)
您可以在两个语句中执行此操作,如下所示:
// Build a lookup: parent ID => whether to show children.
var showChildrenDictionary = PersonList
.Where(p => p.ParentID = 0)
.ToDictionary(p => p.ID, p => p.ShowChildren);
// Get the desired list
var orderdedWithAppropriateChildren = PersonList
// Discard children where not shown
.Where(p => p.ParentID == 0 || showChildrenDictionary[p.ParentID])
// Sort so parents and children are together and ordered by the parent
.OrderBy(p => ((p.ParentID == 0) ? p.ID : p.ParentID))
// Sort so parent is at start of group
.ThenBy(p => p.ParentID != 0)
// Sort so children are in order
.ThenBy(p => p.ID)
.ToList();