private static List <ElementNode> OrderNodes(IEnumerable <ElementNode> leafNodes, ElementNode TopLevelNode) { //Try simple ordering first var count = leafNodes.DistinctBy(x => ((OrderModule)x.Properties.Get(OrderDescriptor.ModuleId)).Order).Count(); if (count == leafNodes.Count()) { //we have a distinct set, so simple ordering should work return(leafNodes.OrderBy(x => ((OrderModule)x.Properties.Get(OrderDescriptor.ModuleId)).Order).ToList()); } //Try to order them by groups. This may not work right all the time either. Dictionary <ElementNode, List <ElementNode> > parentChild = new Dictionary <ElementNode, List <ElementNode> >(); var nonLeafs = TopLevelNode.GetNonLeafEnumerator(); foreach (var leafNode in leafNodes) { var parent = leafNode.Parents.FirstOrDefault(x => nonLeafs.Contains(x)); if (parent != null) { if (parentChild.TryGetValue(parent, out var children)) { children.Add(leafNode); } else { var childList = new List <ElementNode>(); childList.Add(leafNode); parentChild.Add(parent, childList); } } } List <ElementNode> orderedNodes = new List <ElementNode>(); foreach (var childList in parentChild.Values) { orderedNodes.AddRange(childList.OrderBy(x => ((OrderModule)x.Properties.Get(OrderDescriptor.ModuleId)).Order).ToList()); } return(orderedNodes); }