/// <summary> /// Specify explicit ordering of children by Id. /// Id's not corresponding to children will be ignored. /// Not all children need to be specified. However, specified children take precedence; /// unspecified children will be moved (if necessary) behind the specified ones. /// </summary> /// <param name="preferredOrder"></param> public virtual void OrderChildren(params TId[] preferredOrder) { var existingOrder = ChildrenList.Select(n => n.Id).ToArray(); var specifiedIds = preferredOrder.Intersect(existingOrder, Definition.IdEqualityComparer); var unspecifiedIds = existingOrder.Except(preferredOrder, Definition.IdEqualityComparer); var orderMap = specifiedIds.Concat(unspecifiedIds) .Select((id, i) => new { id, i }) .ToDictionary(pair => pair.id, pair => pair.i, Definition.IdEqualityComparer); OrderChildren(seq => seq.OrderBy(n => orderMap[n.Id])); }