I am trying to sort a list of items according to the following (simplified) rules:
Each element has the following properties:
Id (int), ParentId (int?), Name (string)
ParentID is an independent connection of ForeignKey to the identifier. If the item has a ParentId, then the parent will also exist in the list.
I need to sort the list so that all elements that have a parent element appear immediately after their parent. Then all items will be sorted by name.
So, if I had the following:
Id: 1, ParentId: null, Name: Pi Id: 2, ParentId: null, Name: Gamma Id: 11, ParentId: 1, Name: Charlie Id: 12, ParentId: 1, Name: Beta Id: 21, ParentId: 2, Name: Alpha Id: 22, ParentId: 2, Name: Omega
Then I would like them to be sorted as follows:
Identifiers: 2, 21, 22, 1, 12, 11
At the moment, the best thing I can find is sorting by name first and then group by ParentId as follows:
var sortedItems = itemsToSort.OrderBy(x=> x.Name).GroupBy(x=> x.ParentId);
My initial plan was as follows: (in idle code)
var finalCollection = new List<Item> var parentGroup = sortedItems.Where(si => si.Key == null); foreach(parent in parentGroup) { finalCollection.Add(parent); foreach(child in sortedItems.Where(si => si.Key == parent.Id) { finalCollection.Add(child); } }
However parentGroup is not
IEnumerable<Item>
therefore it will not work.
I feel that there is a simpler and more concise way to achieve this, but currently it is eluding me - can anyone help?