Sort List by another List Values - Different Type

Hello. I am trying to Sort a List to another List, which is of different type…

I have 1 list with GameObjects and another List (Same Count), with the same GameObject’s Names.
The list with the names is reordered at some point. After that i want to sort the List with GameObjects to the List with the Names


List<GameObject> myObjects = new List<GameObject>();
List<string> myObjectsNames = new List<string>();

void SomeFunction()
	GameObject[] curSelection = Selection.gameObjects;

	for (int i = 0; i < curSelection.Length; i++)
		myObjects.Add(curSelection*);				// Store the Selected GO to the list*

_ myObjectsNames.Add(curSelection*.name); // Store the Selected GO’s names to the list*_
* }*
* // At some point, the List “myObjectsNames” will be sorted in different way. All the time both Lists will have the same Count.*
* // After that… How can i sort myObjects List to be the same order as the myObjectsNames??*
* // I can use myObjects[#].name to Compare it to myObjectsNames, to get a match…*
* // I can do that with loop and 3rd List, but i was wondering if there is a better / faster way of doing it…*
* // EXAMPLE with Loop*
* List reorderedMyObjects = new List();*
* for (int a = 0; a < myObjectsNames.Count; a++) // Loop through Names*
* {*
* for (int z = 0; z < myObjects.Count; z++) // Loop through Objects*
* {*
* if (myObjectsNames[a] == myObjects[z].name) // Check if the names match*
* reorderedMyObjects.Add (myObjects[z]); // Add the matched object to the 3rd List.*
* }*
* }*
* // This loop works, but i have to assign the sorted gameObjects to third list. I want just to re-order the initial myObjects List*

* }*

EDIT: Seems I missed in my skim reading the fact that your code already has this solution implemented. Sorry about that.

I would suggest creating a third list (during your re-sort) and then iterating over the names, each time finding the appropriate gameObject and popping it into your new list (thus resulting in a list of matching order).

Code removed, already exists in question post.

An alternative might be removing the splitting of the list at all. Is there any particular reason that you are storing the names in a separate list. Could you not just have the one list of game-objects, and then wherever you are re-ordering the names list, you instead re-order this list of game objects as you still would have access to their .name property. Or is there a specific reason you need the names in a list of their own?