Chibuzo
Chibuzo

Reputation: 6117

How to sort an array of the objects of a class according to a numeric property of the class

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

Answers (3)

max
max

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

vc 74
vc 74

Reputation: 38179

objectsOfMyClass.OrderByDescending(obj => obj.NumericProperty)

For your information, this is using Linq to objects

Upvotes: 3

Ray
Ray

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

Related Questions