I want to sort a list, but it's a little complicated. I have a list (of type GameObject) in my class (MyLines) called, 'myWords'. Objects of this class, MyLines, are stored in an array 'LineInfo' Here's how they're declared: Code (CSharp): [System.Serializable] public class MyLines { public GameObject theLineObject; public List<GameObject> myWords; } public MyLines[] LineInfo; ------- I want each example of the List 'myWords' (type GameObject) to be sorted based on x position, in ascending order. Because I have this List (myWords) buried in my class, I'm struggling to use OrderBy() for example. Thank you.
It's not really complicated if all you wanna do is sorting "myWords" by the position's x-value. There is already a Sort method for lists, actually multiple overloads. You can pass an actual type that implements the System.Collections.Generic.IComparer<T> interface, as well as one overload that takes a delegate of type System.Comparison<T>. The latter allows to simply throw in a lambda, if you don't need lots of boilerplate or "configurable" comparers. Here's an example, ascending & stable order: Code (csharp): myWords.Sort((lhs, rhs) => lhs.transform.position.x < rhs.transform.position.x ? -1 : 1); If lambdas scare you, you can move it to a separate method: Code (csharp): // somewhere in your code myWords.Sort(SortByAscendingX); private int SortByAscendingX(GameObject lhs, GameObject rhs) { return lhs.transform.position.x < rhs.transform.position.x ? -1 : 1; } Here are the four variants: Code (CSharp): // ascending & stable _objs.Sort((lhs, rhs) => lhs.transform.position.x < rhs.transform.position.x ? -1 : 1); // ascending & not stable _objs.Sort((lhs, rhs) => lhs.transform.position.x <= rhs.transform.position.x ? -1 : 1); // descending & stable _objs.Sort((lhs, rhs) => lhs.transform.position.x > rhs.transform.position.x ? -1 : 1); // descending & not stable _objs.Sort((lhs, rhs) => lhs.transform.position.x >= rhs.transform.position.x ? -1 : 1);
To avoid making unnecessary assumptions about the implementation details of Sort, you might want to use Code (CSharp): lhs.transform.position.x.CompareTo(rhs.transform.position.x) rather than something like Code (CSharp): lhs.transform.position.x < rhs.transform.position.x ? -1 : 1)
I concur with Antistone. You can get ascending/descending simply by swapping places of lhs and rhs in his first example. Also you can very quickly extend any object by introducing a simple CompareTo method, and making it behave however crazy you want, just be returning -1 (less than), 1 (greater than), or 0 (same) according to some custom values or states.