Doing all those individual moves is going to be inefficient, a better way to do it is do the spans of objects in singular Array.Copy
methods.
I am going to work with Arrays instead of Lists as if you are working with List<T>
you can just use RemoveAt
and Insert
public static void MoveIndex<T>(this T[] array, int sourceIndex, int destIndex)
{
//Some sanity checks before we start.
var arrayLength = array.Length;
if(sourceIndex >= arrayLength || destIndex >= arrayLength || sourceIndex < 0 || destIndex < 0)
throw new IndexOutOfRangeException("The indexes must be within the array);
if(sourceIndex == destIndex)
throw new ArgumentException("The two indexes must not have the same value");
//Store for later useage
var temp = array[sourceIndex];
int offset;
int length;
//Figure out if we are moving left or right
if(souceIndex < destIndex)
{
offset = -1;
length = destIndex - sourceIndex;
}
else
{
offset = 1;
length = sourceIndex - destIndex;
}
//"Move" the elements that need shifting
Array.Copy(array, sourceIndex, array, sourceIndex + offset, length);
//put back the item that we stored earlier;
array[destIndex] = temp;
}
If you can make your collection a ObservableCollection<T>
it has this built right in to it in its Move function