- Home /
Sorting an Arraylist filled with structs.
So, I have a struct like this:
public static struct Score { public string Name; public int HighScore; }
and i place a number of these in an arraylist.
I know there is a sort method attahced to the arraylist, but how do I use it?
I would like to sort the arraylist based on the highscore, but I can't seem to figure out how to do it in an easy way.
Any hints would be great!
it would be nice to be able to do something like this:
HighScoreList.Sort(Score.HighScore);
Thanks. :)
Kjetil
Answer by Mike 3 · Jul 17, 2010 at 07:01 PM
Something like this should do it:
public class StructComparer : IComparer { public int CompareStructs(object x, object y) { if (!(x is YourStruct) || !(y is YourStruct)) return 0; YourStruct a = (YourStruct)x; YourStruct b = (YourStruct)y;
return a.HighScore.CompareTo(b.HighScore);
}
}
//when you want to sort... yourArrayList.Sort(new StructComparer());
Answer by StephanK · Jul 17, 2010 at 06:53 PM
I don't think you can sort structs. For sorting to work in C# you have to implement the IComparer interface, which basically is done by overriding the Compare function. As structs can't have methods you'll have to use a class for that.
$$anonymous$$ost of that isn't true at all. You can sort structs, you don't need to implement the IComparer interface, and structs can have methods (Not that you even need to add your comparer into the struct)
Hm ok, maybe I should read the c# docs more often/carefully and don't assume that concepts are the same in every language, just because they have the same name... What is the purpose of a struct in C# then? (just curious)
Value type ins$$anonymous$$d of a reference type, mainly. makes using Vector3 and Quaternion a heck of a lot easier
The only language that came to my $$anonymous$$d is Delphi/Pascal where a struct (it's called record in Pascal) can't have methods. Nearly all C derived languages allow methods in structs (at least if they have structs, not like Java)
Your answer
Follow this Question
Related Questions
Is not a memeber of Object 1 Answer
Sorting an Transforms array by gameobject name 1 Answer
Sort by Sibling Index 2 Answers
SQLite Sort Ascending order 0 Answers
Grouping neighbouring entrys with the same value in a 2d array. 1 Answer