Get parent and then child objects conditionally

I have a list of objects with the following basic structure:

class Person { public int ID {get; set;} public bool ShowChildren {get; set;} public int ParentID {get; set;} // ...many other properties... } 

I need to return a list of parent Person classes that are ordered by their identifier. If the ShowChildren flag is enabled, also return children under the parent, sorted by their identifier.

This is only one level of depth, that is, children will not have children.

I can write a linq statement to give me all the parents, but I was fixated on how to enable also sorted children when the parent flag is on.

 var People = PersonList .Where(x => x.ParentID == 0) .Orderby(x => x.ID) .ToList(); 
+4
source share
2 answers

Sorry if you only want to return your parents, unless explicitly requested (thanks, @Rawling!), The foreach is good too.

 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)); } } } 
+4
source

You can do this in two steps as follows:

 // 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(); 
+1
source

All Articles