An interesting problem I keep coming across is how to re-order an arraylist item up or down, it's something I've needed to use on a number of applications, so I figured it's about time I got my head round the problem, and it's surprisingly simple.
First we create an Arraylist and populate it:
ArrayList MyRA = new ArrayList();
MyRA.Add("Item1");
MyRA.Add("Item2");
MyRA.Add("Item3");
MyRA.Add("Item4");
MyRA.Add("Item5");
Next we identify the item we want to move:
String myItem = "Item4";
And create an integer to hold the position of the item:
Int32 myIndex = new Int32();
Now get the position:
myIndex = MyRA.IndexOf(myItem);
Almost there, now we insert the Item at that the position before it's current on (Position - 1):
MyRA.Insert((myIndex - 1), myItem);
Finally we need to remove the old item, it's position would have moved up one since we've added an extra item:
MyRA.RemoveAt((myIndex + 1));
So if you're in a hurry and just want the full code here you go:
ArrayList MyRA = new ArrayList();
String myItem = "Item4";
Int32 myIndex = new Int32();
MyRA.Add("Item1");
MyRA.Add("Item2");
MyRA.Add("Item3");
MyRA.Add("Item4");
MyRA.Add("Item5");
myIndex = MyRA.IndexOf(myItem);
MyRA.Insert((myIndex - 1), myItem);
MyRA.RemoveAt((myIndex + 1));
Of course this only moves items down the list, to move them up simply reverse the numbers on the last two lines:
MyRA.Insert((myIndex + 1), myItem);
MyRA.RemoveAt((myIndex - 1));
Happy Coding :0)
Tags: ArrayList, Re-order, c#
Be the first to rate this post
- Currently 0/5 Stars.
- 1
- 2
- 3
- 4
- 5