So I have a generic list, and an oldIndex and a newIndex value.
I want to move the item at oldIndex, to newIndex.
This is how I implemented a move element extension method. It handles moving before/after and to the extremes for elements pretty well.
public static void MoveElement(this IList list, int fromIndex, int toIndex)
{
if (!fromIndex.InRange(0, list.Count - 1))
{
throw new ArgumentException("From index is invalid");
}
if (!toIndex.InRange(0, list.Count - 1))
{
throw new ArgumentException("To index is invalid");
}
if (fromIndex == toIndex) return;
var element = list[fromIndex];
if (fromIndex > toIndex)
{
list.RemoveAt(fromIndex);
list.Insert(toIndex, element);
}
else
{
list.Insert(toIndex + 1, element);
list.RemoveAt(fromIndex);
}
}