Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Sort vs JavaScript Sort

I am having following array as input to sort values in descending order:

var cars = ["8587009748118224023Po","8587009748118224023PP","8587009748118224023P,","8587009748118224023P$","8587009748118224023P<","8587009748118224023P?"]

In C#, I am using OrderByDescending and getting following output

C# code:

var rslt= cars.OrderByDescending(a => a);

Result (commas added after each value):

8587009748118224023PP,
8587009748118224023Po,
8587009748118224023P<,
8587009748118224023P?,
8587009748118224023P,
,
8587009748118224023P$,

In Javascript, I am using sort and reverse and getting following different result

javascript code:

cars.sort();
cars.reverse();

Result:

8587009748118224023Po,
8587009748118224023PP,
8587009748118224023P?,
8587009748118224023P<,
8587009748118224023P,
,
8587009748118224023P$

Can anyone help me how to sort values in C# as like JavaScript?

like image 755
kombsh Avatar asked Dec 23 '22 15:12

kombsh


2 Answers

Try changing the StringComparer:

Array.Sort(cars, StringComparer.Ordinal);
Array.Reverse(cars);
like image 106
Michael Silver Avatar answered Dec 28 '22 10:12

Michael Silver


It looks like the Javascript is doing a case insensitive sort. For C# you need to explicitly tell it to do this. So this should work;

var rslt = cars.OrderByDescending(a => a, StringComparer.OrdinalIgnoreCase);

Edit:

After update from OP then he discovered that the ignore case was not required. So the following worked;

var rslt = cars.OrderByDescending(a => a, StringComparer.Ordinal);
like image 45
jason.kaisersmith Avatar answered Dec 28 '22 10:12

jason.kaisersmith