I have two Lists, a primary list and a list of items to move, which is a subset of the primary list:
var primaryList = new List<foo> { f1, f2, f3, f4, f5, f6, f7 };
var itemsToMove = new List<foo> { f1, f4, f6, f7 };
I want to change the order of the items in primaryList so that each element that is also in itemsToMove moves one position closer to the start of the list, but I need for items to stay in order relative to other members of the itemsToMove collection.
The result I want is:
Iteration #1:
primaryList { f1, f2, f4, f3, f6, f7, f5 };
Iteration #2:
primaryList { f1, f4, f2, f6, f7, f3, f5 };
Iteration #2:
primaryList { f1, f4, f6, f7, f2, f3, f5 };
Here's the code I'm currently using:
// Catch items that are already in the last or first position
foreach (var item in primaryList)
{
if (primaryList.IndexOf(item) < 1)
{
itemsToMove.Remove(item);
}
}
foreach (var item in itemsToMove)
{
int index = primaryList.IndexOf(item);
if (index > 0)
{
primaryList.Remove(item);
primaryList.Insert(index - 1, item);
}
}
When I use this code, the result I get is:
primaryList { f1, f2, f4, f3, f5, f6, f7, };
I've looked at this question, but the answer there doesn't seem to actually do anything at all, so I changed the code to move closer to a solution.
What am I doing wrong here? Is there a more efficient way to handle this operation?