4

我有一个具有以下基本结构的对象列表:

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();
4

2 回答 2

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));
        }
    }
}
于 2012-07-05T17:54:19.883 回答
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();
于 2012-07-05T18:12:02.560 回答