Reputation: 607
I have an array of objects containing the following data.
unsortedArray =
A : 1
B : 2
C : 3
D : 4
E : 5
F : 6
G : 7
H : 8
I : 9
J : 10
K : 11
L : 12
M : 13
N : 14
O : 15
P : 16
Q : 17
R : 18
S : 19
T : 20
U : 21
V : 22
W : 23
X : 24
Y : 25
Z : 26
I'm trying to sort these objects so that the objects with the higher integer values appear further up in the list, but am receiving the following output with the sort..
sortedArray =
Z : 26
X : 24
W : 23
V : 22
U : 21
T : 20
S : 19
R : 18
Q : 17
P : 16
O : 15
N : 14
M : 13
L : 12
K : 11
J : 10
I : 9
H : 8
G : 7
F : 6
E : 5
D : 4
C : 3
B : 2
Y : 25
A : 1
Below is the code I am using..
var sortedArray= unsortedArray;
Array.Sort(sortedArray, (x, y) => y.Point >= x.Point ? y.Point : x.Point);
Note: In the code, Point
refers to the integer value in the object.
What am I doing incorrectly?
Upvotes: 1
Views: 64
Reputation: 45967
replace
Array.Sort(sortedArray, (x, y) => y.Point >= x.Point ? y.Point : x.Point);
with
Array.Sort(sortedArray, (x, y) => y.Point >= x.Point ? 1 : -1);
Upvotes: 1
Reputation: 272555
The second argument you pass to Array.Sort
is an IComparer<T>
. From the documentation:
Return Value Type: System.Int32 A signed integer that indicates the relative values of x and y, as shown in the following table.
If you return a value according to the above table and use Sort
, the array will be sorted in ascending order, which is the opposite of what you want. This means that you should return a negative value if x is larger than y, and a positive value if x is less than y!
Array.Sort(sortedArray, (x, y) => y.Point - x.Point);
Upvotes: 1