- Home /
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?
Thanks
How often will you be perfor$$anonymous$$g the sort? Is it time critical? Will the items be randomly distributed or partially ordered?
Any of these factors could influence the optimal solution.
Bubble Sort is an easy to understand and implement sort algorithm, or you can use LINQ's OrderBy() as a ready made solution.
Answer by joshpsawyer · Apr 27, 2014 at 04:50 PM
Use the Array.Sort() method that takes a Comparison<T>:
Array.Sort(myRareBlockArray,
delegate(RareBlock x, RareBlock y) { return x.chance.CompareTo(y.chance); });
Also, if you know that you'll always want to sort the RareBlock class in this way, you might implement the IComparable<t> interface... it will simplify your calls, at least.
Are you using "`Array.Sort()`"? Sort
is a static method of the Array
type.
Please change the first line to:
Array.Sort(sortedBlockTypes,
Ok, then you need using System;
at the top of your file.
Answer by Cassos · Apr 28, 2020 at 05:39 PM
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[i].id + i, _ds[i]);
List<string> keys = new List<string>();
foreach (KeyValuePair<string, Dialogue> _d in _dic)
keys.Add(_d.Key);
keys.Sort();
List<Dialogue> ds = new List<Dialogue>();
foreach (string s in keys)
ds.Add(_dic[s]);
return ds.ToArray();
}
Have fun with it! ^^
Greetings, Max
Answer by Acegikmo · Apr 28, 2020 at 06:22 PM
Linq version, if you want that!
myArray = myArray.OrderBy( x => x.chance ).ToArray();
Good one! thanks. And I figured out if you want the order descending:
myArray = myArray.OrderByDescending( x => x.chance ).ToArray();
Answer by Adamcbrz · Apr 27, 2014 at 04:49 PM
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.
http://msdn.microsoft.com/en-us/library/cxt053xf(v=vs.110).aspx
Your answer
