How to sort a list of keyValuePair?

The key is a GameObject and the value is a Vector3. The y and z axis are constant, so only the x changes. Based on this, I want to sort them from left to right. Am understanding that I have to use a lambda expression to achieve this, but I don´t know what that is and am having a hard time figuring it out. Thanks in advance.

You never have to use a lambda expression. They just make it easier to write inplace anonymous methods.

So based on your descrption you have a

List<KeyValuePair<GameObject, Vector3>> list;

which you want to sort based on the x value of the Vector3 value of each pair? You should be able to do this:

list.Sort((a, b) => a.Value.x.CompareTo(b.Value.x));

As I said, lambda expression are just in place shortcuts for anonymous methods. In addition they can be closures, but that’ irrelevant here. You can instead use a method like this

private static int SortOnValueX(KeyValuePair<GameObject, Vector3> a,KeyValuePair<GameObject, Vector3> b)
    return a.Value.x.CompareTo(b.Value.x);

This is the exact same method and can be used instead:


That’s why lambda expressions are usually simpler.