C # array move element (not ArrayList / general list)

Have an object that is an array (not an arraylist or generic) that could contain a collection of everything ...

[[One],[Two],[Three],[Four]]

Want to move [Four] before [Two], for example. oldIndex = 3, newIndex = 1 so the result will be ...

[[One],[Four][Two],[Three]]

What is the most efficient way to do this in .NET 2.0, for example.

PropertyInfo oPI = ObjectType.GetProperty("MyArray", BindingFlags.Public | BindingFlags.Instance);
object ObjectToReorder = oPI.GetValue(ParentObject, null);
Array arr = ObjectToReorder as Array;
int oldIndex = 3;
int newIndex = 1;
//Need the re-ordered list still attached to the ParentObject

early

+3
source share
2 answers
void MoveWithinArray(Array array, int source, int dest)
{
  Object temp = array.GetValue(source);
  Array.Copy(array, dest, array, dest + 1, source - dest);
  array.SetValue(temp, dest);
}
+6
source

try it

Array someArray = GetTheArray();
object temp = someArray.GetValue(3);
someArray.SetValue(someArray.GetValue(1), 3);
someArray.SetValue(temp, 1);
+4
source

All Articles