I need to rearrange a list of items so that the selected item goes to the end of the list and the last item replaces the previous one and the previous item replaces the one before it and so on.
For example, if I have a list of ten items and the selected item is in position 5, this item goes to position 9 and 9 will replace 8 then 8 replaces 7 and 7 replaces 6 and six takes position 5. I managed to get the desired result using this code:
List<int> numList = new List<int>();
int selectedNum = 5;//Selected at runtime
for (int i = 0; i < 10; i++) numList.Add(i);
int numListCount = numList.Count-1;
int tempNum = numList[numListCount];
List<int> tempList = numList.GetRange(selectedNum + 1,(numList.Count-selectedNum) - 2);
numList[numListCount] = selectedNum;
numList.RemoveRange(selectedNum, (numList.Count-selectedNum)-1);
numList.InsertRange(selectedNum, tempList);
numList.Insert(numListCount - 1, tempNum);
The result is:
0,1,2,3,4,6,7,8,9,5
I'm sure my code is ugly and inefficient: I have two questions:
You can use the Remove Method to remove the selected item and the Add Method to append it at the end:
List<int> numList = new List<int>();
for (int i = 0; i < 10; i++) numList.Add(2 * i);
int selectedNum = 6; // selected at runtime
numList.Remove(selectedNum);
numList.Add(selectedNum);
Before:
0 2 4 6 8 10 12 14 16 18
After Remove(6):
0 2 4 8 10 12 14 16 18
After Add(6):
0 2 4 8 10 12 14 16 18 6
If you want to move the item at a selected index, you can use the RemoveAt Method instead of the Remove Method:
List<int> numList = new List<int>();
for (int i = 0; i < 10; i++) numList.Add(2 * i);
int selectedIndex = 5; // selected at runtime
int selectedNum = numList[selectedIndex];
numList.RemoveAt(selectedIndex);
numList.Add(selectedNum);
Before:
0 2 4 6 8 10 12 14 16 18
After RemoveAt(5):
0 2 4 6 8 12 14 16 18
After Add(10):
0 2 4 6 8 12 14 16 18 10
Using LINQ, you would create a new list that has the selected item removed and appended. An in-place update as shown above is much more efficient though.
List<int> numList = new List<int>();
for (int i = 0; i < 10; i++) numList.Add(2 * i);
int selectedIndex = 5; // selected at runtime
List<int> newNumList = numList.Take(selectedIndex)
.Concat(numList.Skip(selectedIndex + 1))
.Concat(numList.Skip(selectedIndex).Take(1))
.ToList();
numList:
0 2 4 6 8 10 12 14 16 18
newNumList:
0 2 4 6 8 12 14 16 18 10
From what I understand you just want to move a given item to the bottom of a list right?
List<int> list = new List<int>();
for (int i = 0; i < 10; i++)
numList.Add(i);
int temp = list[5];
list.RemoveAt(5);
list.Add(temp);
EDIT: My understanding was that you knew the position of the item you wanted to move (5). If you know the value then the other answer posted is the right one for that
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With