'Remove incremental number from List and decrement following

First of all this is a common question not related to the Dart language, but because I need it for Dart, I tagged it like so.

I have a List of objects which contain an incremental number

List<MyObject> myObjectList = [
  MyObject(1),
  MyObject(2),
  ...
  MyObject(10),
];

class MyObject {
  int order;

  MyObject(this.order);
}

I now want to remove an item from the List and the following order numbers to decrease. So lets say I remove item with order number 5, the ones with 6, 7, 8, 9 and 10 should decrement by one, resulting in a List like:

List<MyObject> myObjectList = [
  MyObject(1),
  MyObject(2),
  ...
  MyObject(9),
];

This can easily be done with a for-loop checking the items number:

var removedOrder = 5;

for (var item in myObjectList){
  if (item.order > removedOrder) {
    item.order -= 1;
  }
}

This is really simple to understand and should work, but honestly, simple is boring and ugly. Is there a way to achieve the desired result without the need to write a for loop? Also what are your suggestions to optimize that logical part?



Solution 1:[1]

One solution would be: When you delete and item from the list on position lets say 5, then you can take the last item in the list and change its value to 5. This removes the need to run through all the items and decreasing its values.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jan Smitka