tags:

views:

2285

answers:

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

+3  A: 

Try this

Array someArray = GetTheArray();
object temp = someArray.GetValue(3);
someArray.SetValue(someArray.GetValue(1), 3);
someArray.SetValue(temp, 1);
JaredPar
Hi Jared, thanks for your answer.Unfortunately I think your answer is incorrect.I've given details in the post below.Maybe you could try again if you want to.
Mark
A: 

Hi Jared, thanks for your answer. Unfortunately I think your answer is incorrect.

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
+1  A: 
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
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 classthanks
Mark
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