3

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

Mark
  • 245
  • 4
  • 10

2 Answers2

6
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);
}
Wyzfen
  • 363
  • 3
  • 9
  • thats more like it, just goes to show that its not about how many questions you've answered its about how good the answers are. I had no idea you could copy an array onto itself. I guess thats how the ArrayList does Insert?,i tried the code using reflector but I could find the ArrayList class thanks – Mark Mar 20 '09 at 22:06
  • That question looks like it was too easy for you, if you can could you try to answer this other question i've posted... http://stackoverflow.com/questions/668356/use-reflection-to-set-the-value-of-a-field-in-a-struct-which-is-part-of-an-array – Mark Mar 20 '09 at 23:36
  • 2
    I really don't understand how this answer can get any up-votes at all. The solution given here only works in OP's very specific example. The method should be named `MoveWithinArrayInOneSpecificCase(...)`. For example, if we try to move an element from front to back we get negative `length`-parameter (just one of the possible errors in this method). – Whyser Feb 25 '16 at 16:49
3

Try this

Array someArray = GetTheArray();
object temp = someArray.GetValue(3);
someArray.SetValue(someArray.GetValue(1), 3);
someArray.SetValue(temp, 1);
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • If I step through your code with the array i gave then i get a different array to the one I required... ### 1. Array someArray = GetTheArray(); [[One],[Two],[Three],[Four]] ### 2. object temp = someArray.GetValue(3); [[One],[Two],[Three],[Four]] temp is [Four] ### 3. someArray.SetValue(someArray.GetValue(1), 3); someArray.GetValue(1) is [Two] [[One],[Two],[Three],**[Two]**] ### 4. someArray.SetValue(temp, 1); [[One],**[Four]**,[Three],[Two]] ### I wanted [[One],[Four],[Two],[Three]] (i.e. Move [Four] in-front of [Two]) – Mark Aug 15 '12 at 14:26