Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a list compared to an existing list in C#?

I have a List<int> allIDs containing a list of IDs in it's original order. I am creating a element chooser, which lets the user add and remove IDs from this list to another List<int> selectedIDs. Now, I have this all up and working, but whenever a user removes and later adds the same element, it's just added to the end of the list (selectedIDs.Add( id )).

I want to insert the element to its original position, using allIDs as a reference to where it used to be.

Here is some excerpts of the lists to put it all in context:

List<int> allIDs = new List<int> {10, 11, 9, 155, 12, 299, 15...};
List<int> selectedIDs = new List<int> { 10, 9, 155, 299, 15... }

Now let's say I removed id=299 from the selectedIDs-list, for later to try to add it again. How do I insert it between 155 and 15? I know I can insert wherever in the list with the list.Insert(obj, index) method, but how do I do this programmatically in the simplest way possible?

like image 820
Kris Selbekk Avatar asked Dec 21 '22 23:12

Kris Selbekk


1 Answers

If i've understood your requirement correctly:

var ordered = selectedIDs.OrderBy(sID => allIDs.IndexOf(sID));

This will order the list of selected ID's by the index of each id in the original, complete list.

like image 53
Tim Schmelter Avatar answered Jan 07 '23 17:01

Tim Schmelter