Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Array Move Item (Not ArrayList/Generic List)

Tags:

arrays

c#

Have an object which is an array (not arraylist or generic) that could hold a set of anything...

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

Want to move [Four] to in front of [Two] e.g. oldIndex = 3, newIndex = 1 so the result would be...

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

Whats the most effient way to do this in .NET 2.0, e.g.

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

thanks in advance

like image 317
Mark Avatar asked Dec 05 '25 05:12

Mark


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);
}
like image 83
Wyzfen Avatar answered Dec 07 '25 18:12

Wyzfen


Try this

Array someArray = GetTheArray();
object temp = someArray.GetValue(3);
someArray.SetValue(someArray.GetValue(1), 3);
someArray.SetValue(temp, 1);
like image 32
JaredPar Avatar answered Dec 07 '25 17:12

JaredPar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!