Reputation: 6117
I store objects of a class in an object array of the same class.
MyClass[] objectsOfMyClass = new MyClass[9];
Now I want to sort in descending order the objects stored in the array according to a numeric property of the objects.
Upvotes: 0
Views: 89
Reputation: 34427
You can use Array.Sort()
method overload, which accepts Comparison<T>
:
Array.Sort(objectsOfMyClass, (o1, o2) => o2.NumericProperty.CompareTo(o1.NumericProperty));
Upvotes: 1
Reputation: 38179
objectsOfMyClass.OrderByDescending(obj => obj.NumericProperty)
For your information, this is using Linq to objects
Upvotes: 3
Reputation: 46585
You need OrderByDescending. It will not sort the array but return an IEnumerable that's ordered correctly.
var orderedArray = objectsOfMyClass.OrderByDescending(m => m.MyProperty).ToArray();
The ToArray
might not be necessary depending on what you're doing with the result.
Upvotes: 1