delphitcollectiontcollectionitem

How do I reorder items in a TCollection?


I am trying to implement MoveItemUp and MoveItemDown methods that move a selected row up or down one index within a TCollection.

The following code added to my subclass of TCollection does not work:

procedure TMyCollection.MoveRowDown(index: Integer);
var
 item:TCollectionItem;
begin
  if index>=Count-1 then exit;
  item := Self.Items[index];
  Self.Delete(index); // whoops this destroys the item above.
  Self.Insert(index+1);
  Self.SetItem(index+1,item); // this actually does an assign from a destroyed object.
end;

I am fairly sure this must be possible at runtime, as its done in designtime by the Delphi IDE itself which provides a way to reorder Collection items in a list. I am hoping to do this by simply reordering existing objects, without creating, destroying, or Assigning any objects. Is this possible from a subclass of Classes.pas TCollection? (If not, I may have to make my own TCollection from a source clone)


Solution

  • According to the VCL source, you don't need to manually do that. Simply set the Index property like @Sertac suggested and it should work just fine. If you have the source, check out the code of TCollectionItem.SetIndex.