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

2 Answers 2

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);
}
Sign up to request clarification or add additional context in comments.

3 Comments

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
That question looks like it was too easy for you, if you can could you try to answer this other question i've posted... stackoverflow.com/questions/668356/…
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).
3

Try this

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

1 Comment

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])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.