- Home /
Duplicate Question
How to alphabetically sort your List?
Here's my code
using System.Collections.Generic;
public class DotHolder : MonoBehaviour {
public List myList = new List();
void Start () {
foreach (Transform child in gameObject.transform)
{
myList.Add(child.gameObject);
}
}
}
now that myList contains a gameobjects of it's children, my question is,
how can i sort all the children alphabetically?
example current output:
myList[0] = "dog4" myList[1] = "dog5" myList[2] = "dog3" myList[3] = "dog1" myList[4] = "dog5"
example target output:
myList[0] = "dog1" myList[1] = "dog2" myList[2] = "dog3" myList[3] = "dog4" myList[4] = "dog5"
http://video.unity3d.com/video/7720450/tutorials-using-unity-answers tells you how to format code.
Answer by Graham-Dunnett · Feb 22, 2013 at 02:01 PM
// c# example
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class sortlist : MonoBehaviour {
public List<string> myList = new List<string>();
void Start () {
myList.Add("Tyrannosaurus");
myList.Add("Amargasaurus");
myList.Add("Mamenchisaurus");
myList.Add("Deinonychus");
myList.Add("Compsognathus");
foreach(string dinosaur in myList)
{
Debug.Log(dinosaur);
}
myList.Sort();
foreach(string dinosaur in myList)
{
Debug.Log(dinosaur);
}
}
}
MSDN is your friend.
Hey there, thanks for this, it's actually very helpful. I really appreciate it!
Super outdated, use Linq instead.
with using System.Linq;
you get a bunch of useful extension methods for collections, such as the OrderBy
and OrderByDescending
methods.
Use them like this:
List<GameObject> objSortedList = objListObject.OrderBy(o=>o.name).ToList();