Sorting a list according to the sorting of another one

Hello everyone,

I have two lists,

one contains floats, the other gameobjects. Both lists have the same size.

I want to sort the floats, but if I do so, the elements of the first list will not correspond to the correct game objects anymore. Therefore I need to sort the gameobjects accordingly. How to do this?

That’s not the way you should store your data! What about using a Dictionary? Or use a list with KeyValuePairs as items. Look at the answer here: How do you sort a dictionary by value?

I do not know about dictionaries, so maybe is it time for me to check that out. I’ll do that now. Thanks for the tip!

Still, is there any built-in function in C# in order to do what I’m trying to do?

I’m pretty sure that there is no such thing.

Hello, if your float and gameObject have a meaning together, you should make a class out of it.

This class can have only thoose 2 values as members:

[System.Serializable] //This allows you to modify objects of this class in the inspector
public class FloatAndGameObjectClassName
{
    public float _theFloatValue;
    public GameObject _theGameObject;
}

And you can make a list out of it:

public List<FloatAndGameObjectClassName> _yourList;

void Start()
{
     this._yourList.Add(new FloatAndGameObjectClassName()
     {
           _theFloatValue = 0f,
           _theGameObject = blabla
     });
}

Then you can sort it using the float value and the GameObject will stay in sync with its float :

//Linq method
this._yourList.Sort((data1, data2) => data1._theFloatValue.CompareTo(data2._theFloatValue));

If he carefully read my link to the stackoverflow answer he should have seen a similar approach already:

List<KeyValuePair<float, GameObject>>

By using KeyValuePair he doesn’t have to write a custom class.

OK, things are moving in the good direction: I have now a dictionary where the keys are the gameobjects and the values are the floats. Now I need to sort this dictionary by value. However, I have difficulties understanding how to change the code:

List<KeyValuePair<string, string>> myList = aDictionary.ToList(); //

myList.Sort((firstPair,nextPair)=>{return firstPair.Value.CompareTo(nextPair.Value);});

If I do

List<KeyValuePair<GameObject, float>> myList = myUnsortedDict.ToList(); //

myList.Sort((firstPair,nextPair)=>{return firstPair.Value.CompareTo(nextPair.Value);});

where is the sorted dictionary after the code has run?

You can’t sort a dictionary! There’s also a SortedDictionary class but even this container can’t be sorted by value. So you have to work on the list then.

BTW: I highly suggest you to read a book about C# or at least about its containers (or containers in general). Using the right datastructure is a very common and important task for a programmer.

I’m confused because I just managed to get a sorted dictionary with this code:

        List<KeyValuePair<GameObject, float>> tempList = distancesHomes.ToList(); //
        tempList.Sort((firstPair,nextPair)=>{return firstPair.Value.CompareTo(nextPair.Value);});


        for (i=0; i<tempList.Count; i++) {
            distancesHomesSorted.Add (tempList[i].Key, tempList[i].Value);
        }

distancesHomesSorted is a dictionary identical to distancesHomes, except that when I go through the Sorted version using a for loop, I get the Keys and Values from the smallest value to the largest, exactly what I wanted. Will I however encounter an issue?

Make a sorted list of keyvaluepairs. Does everything your looking for. Declaration looks like

SortedList<KeyValuePair<float,GameObject>> = new SortedList<KeyValuePair<float,GameObject>>();

@Pysassin : A SortedList probably won’t suit his needs as you can’t have duplicate items in it, i.e. two equal keys, unless you write your own custom IComparer!

@Thomas12 : In general the order in which the items of a Dictionary are returned is undefined. So you shouldn’t count on what you’ve written! Anyway, your code looks horrible. Do you mind telling us what you are trying to accomplish?

This is true for Dictionary as well.

Judging by the variable names being used it looks like the goal is to maintain a list of GameObjects sorted by some kind of distance. Instead of messing around with keys and whatnot I would just keep a List and sort it every time you add a new item to it.

@BrightBit Is that true for a list as well or is the order in which the items of a list are returned stable?

The solution from Pysassin may be what I need in the end. And yes my keys will always be unique since each key is a different game object in the scene, so it’s fine.

Lists maintain their order. The item at index 0 will always be there until someone moves it or removes it.

The point is - if you want to sort by float then the float has to be your key, not the GameObject. I’m still asking if you need keys in the first place. What does the float value represent?

Say I’m at origin of the world. I need to be able to access the instance of each game object in the world, one at the time, from the closest to the fartest. Several game objects can have the same distance from origin, so using the distances as keys will not work. However using the game object themselves as key seems to work. The world is moreover dynamic in the sense that every now and then, new objects will appear and some will be deleted.

In any case I successfully managed to do what I wanted using KeyValuePair, as suggested by @Pysassin .

I thank everyone for their help, I learned a lot from this post!

@KelsoMRK : You’re right about the Dictionary. It was not until Pysassin’s post about the SortedList that made me realise Thomas12 might need duplicates. And I totally forgot about my own suggestions. :face_with_spiral_eyes:

@Thomas12 : Yes, the order of items in a list is defined! Glad you finally made it running. Is it selfish to emphasize that it was me who suggested a list with KeyValuePairs first (see my first post)? :wink:

Its ok Bright I’ll share credit with ya :wink:

Okay, that’s fine for me. :slight_smile:

You are right BrighBit, you were the first to suggest a list with KeyValuePairs, I got obsess with dictionaries and forgot about that second suggestion!

In any case, special thanks to Pysassin and BrightBit :slight_smile:

This is such an old post, but I wanted to weigh in. If you want to sort different array types based on each other, you can use a for loop with arrays of equal sizes. You’ll have presorted array of the thing(s) you want sorted, and a post sorted. I use this to sort by multiple criteria, ie names first, then other attributes, especially when I want to control the order based on my own preferences rather than alphamunerics. You can use variable lengths this way and do a lot of powerful and very highly controlled data management. Could become processor and memory intensive with large arrays. Make sure to check that the entry is only being assigned once and run until you flip all entries in the presort.