Does List<T> guarantee insertion order?

SuperSuperDev1234 picture SuperSuperDev1234 · Jun 25, 2009 · Viewed 117.3k times · Source

Say I have 3 strings in a List (e.g. "1","2","3").

Then I want to reorder them to place "2" in position 1 (e.g. "2","1","3").

I am using this code (setting indexToMoveTo to 1):

listInstance.Remove(itemToMove);
listInstance.Insert(indexToMoveTo, itemToMove);

This seems to work, but I am occasionally getting strange results; sometimes the order is incorrect or items from the list are getting deleted!

Any ideas? Does List<T> guarantee order?

Related:

Does a List<T> guarantee that items will be returned in the order they were added?

Answer

Bevan picture Bevan · Jun 25, 2009

The List<> class does guarantee ordering - things will be retained in the list in the order you add them, including duplicates, unless you explicitly sort the list.

According to MSDN:

...List "Represents a strongly typed list of objects that can be accessed by index."

The index values must remain reliable for this to be accurate. Therefore the order is guaranteed.

You might be getting odd results from your code if you're moving the item later in the list, as your Remove() will move all of the other items down one place before the call to Insert().

Can you boil your code down to something small enough to post?