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?
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.
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