Sort an array of classes by a variable value.

This is my class:

public class RareBlock

		public string name;
		public Vector3 blocks;
		public int chance;

I have an array of many instances of this class. How do I sort the array according to the value of chance?


Use the Array.Sort() method that takes a Comparison:

delegate(RareBlock x, RareBlock y) { return x.chance.CompareTo(y.chance); });

If anyone needs this in 2020, I created a function for a recent project, sorting and returning an array of custom classes, by first making it into a dictionary:

    public Dialogue[] SortDialogues(Dialogue[] _ds)
        Dictionary<string, Dialogue> _dic = new Dictionary<string, Dialogue>();

        for (int i = 0; i < _ds.Length; i++)
            _dic.Add(_ds<em>.id + i, _ds*);*</em>

List keys = new List();
foreach (KeyValuePair<string, Dialogue> _d in _dic)
List ds = new List();
foreach (string s in keys)
return ds.ToArray();
Have fun with it! ^^

Linq version, if you want that!

myArray = myArray.OrderBy( x => x.chance ).ToArray();

Here is the link to the documentation for having a compare method with array.sort. From there you can tell it what how to compare.

I don’t mean to revive this conversation but its the only one remotely like my problem but i cant get it to work
I have a scriptable object called Potions which contains

    public string PotionName;
    public string PotionDescription;
    public int Cost

In another script i have an array which i want to sort

public Potions[] myPotions = new Potions[64];

i would like to sort this by the cost

i tried this

        delegate (Potions x, Potions y)
        { return x.Cost.CompareTo(y.Cost); });

i get this error.

NullReferenceException: Object reference not set to an instance of an object
BrothersManager.m__0 (.Potions x, .Potions y) (at Assets/New Game Manager/BrothersManager.cs:154)