排序算法
原理:
1 4 = 1 2 1 +1 = 2 3 2 +1 = 3 4 3 +1 = 4 5 5 = 5 prev: null next: 1 newOrder 1 < originOrder 4 >0 && < 4 1 2 -1 = 1 2 3 -1 = 2 3 1 = 3 4 4 = 4 5 5 = 5 prev: 3 next: 4 newOrder 3 > originOrder 1 >1 && <4 1 1 = 1 2 3 -1 = 2 3 4 -1 = 3 4 5 -1 = 4 5 2 = 5 prev: 5 next: null newOrder 5 > originOrder 2 >2 && <6 newOrder > originOrder,中间部分序号-1 newOrder < originOrder,中间部分序号+1
伪代码:
private async Task SortAsync(Guid id, int? toPreviousOrder, int? toNextOrder) { var newOrder = GetNewOrder(toPreviousOrder, toNextOrder); var entity = await _store.FindAsync(id, required: true); if (entity.Order == newOrder) return; IEnumerable<Entity> entitiesBetween; if (newOrder > entity.Order) { entitiesBetween = await GetEntitiesAsync(x => x.Order > entity.Order && x.Order < newOrder + 1); } else { entitiesBetween = await GetEntitiesAsync(x => x.Order > newOrder - 1 && x.Order < entity.Order); } if (entitiesBetween.Any()) { foreach (var entityBetween in entitiesBetween) { if (newOrder > entity.Order) { entityBetween.Order -= 1; } else { entityBetween.Order += 1; } entityBetween.WhenUpdated = DateTime.Now; } _store.UpdateRange(entitiesBetween); } entity.Order = newOrder; entity.WhenUpdated = DateTime.Now; _store.Update(entity); await _store.SaveChangesAsync(); } private int GetNewOrder(int? toPreviousOrder, int? toNextOrder) { if (toPreviousOrder.HasValue && toNextOrder.HasValue) { return toPreviousId.Value; } else if (toPreviousOrder.HasValue && !toNextOrder.HasValue) { return toPreviousOrder.Value; } else if (!toPreviousOrder.HasValue && toNextOrder.HasValue) { return toNextOrder.Value; } else throw new InvalidOperationException(); }
纠正代码(调用 GetNewOrderId 的地方需要改成调用这个):
public static Guid GetNewOrderId(Guid? toPreviousId, Guid? toNextId, int? toPreviousOrder, int currentOrder) { if (toPreviousId.HasValue && toNextId.HasValue) { if (toPreviousOrder < currentOrder) { return toNextId.Value; } else { return toPreviousId.Value; } } else if (toPreviousId.HasValue && !toNextId.HasValue) { return toPreviousId.Value; } else if (!toPreviousId.HasValue && toNextId.HasValue) { return toNextId.Value; } else throw new InvalidOperationException(); }