# Sort a list of class by a vector variable in the class

So I have a list of a class, say MyObjectClass. The MyObjectClass has a Vector3 variable. I want to sort my list of MyObjectClass objects by the x in this Vector3 Variable. I want it sorted by lowest to highest x and if two variables have the same x, I want them sorted by lowest to highest y.

So if MyObjectClass list contains MyClassObject’s that’s vector variables is say the following Vectors: (135,62,0) , (120,47,0) (150,30,0), and (120,28,0)

I want the list to be sorted so that calls to the get function for each objects vector variable results in this order:
(120,28,0) , (120,47,0), (135,62,0) , and (150, 30, 0).

Is there a way, perhaps with linq or some other method, to sort them with this criteria, or will I have to write my own sorting algorithm to sort them?

You definitely don’t have to reinvent the wheel to implement your own sort. Linq has this functionality. To go about it:

``````using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class ExampleClass : MonoBehaviour {
private List<MyObjectClass> m_myObjectClasses;

void Start() {
m_myObjectClasses = new List<MyObjectClass>();

foreach (MyObjectClass m in SortedMyObjectClasses)
Debug.Log(m.m_vector);

// Output:
// (120, 28, 0)
// (120, 47, 0)
// (135, 62, 0)
// (150, 30, 0)
}
public IOrderedEnumerable<MyObjectClass> SortedMyObjectClasses
{
get
{
return m_myObjectClasses.OrderBy(m => m.m_vector.x).ThenBy(m => m.m_vector.y);
}
}
}

public class MyObjectClass
{
public Vector3 m_vector;

public MyObjectClass(Vector3 vector)
{
m_vector = vector;
}
}
``````

Obviously your class would differ, and you might not use a constructor to initialize the vector in MyObjectClass, but the accessor on SortedMyObjectClasses is what you need.

Simpler method:

``````void Start() {
myObjectClasses = new List<MyObjectClass>();
// ....
myObjectClasses.Sort( Compare );
}

private int Compare( MyObjectClass a, MyObjectClass b )
{
Vector3 va = a.Vector ;
Vector3 vb = b.Vector ;

if( Mathf.Abs( va.x - vb.x ) < 0.001f )
{
if( Mathf.Abs( va.y - vb.y ) < 0.001f  ) return 0 ;
return va.y < vb.y ? -1 : 1 ;
}
return va.x < vb.x ? -1 : 1 ;
}
``````