4

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?

ruffin
  • 16,507
  • 9
  • 88
  • 138
Kevin M
  • 5,436
  • 4
  • 44
  • 46

2 Answers2

6

Try changing the StringComparer:

Array.Sort(cars, StringComparer.Ordinal);
Array.Reverse(cars);
Michael Silver
  • 483
  • 5
  • 15
  • 1
    You are right, the following code gives the correct result in my case in C#. var rslt = cars.OrderByDescending(a => a, StringComparer.Ordinal); – Kevin M Aug 11 '17 at 05:57
  • And though @Rajesh [deleted his answer explaining this](https://stackoverflow.com/a/45627427/1028230), this gives you a hint of how to accomplish the flip side of this too -- if you want JavaScript to sort like C# does by default, you use a sorting algorithm that employs [`localCompare`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare). – ruffin Nov 09 '20 at 17:29
4

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);
jason.kaisersmith
  • 8,712
  • 3
  • 29
  • 51
  • It gives following different result (not like javascript) 8587009748118224023PP,8587009748118224023Po,8587009748118224023P?,8587009748118224023P<,8587009748118224023P,,8587009748118224023P$ – Kevin M Aug 11 '17 at 05:22
  • [`If compareFunction is not supplied, elements are sorted by converting them to strings and comparing strings in Unicode code point order`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Description) – ASDFGerte Aug 11 '17 at 05:27
  • 1
    @jason.kaisersmith, your answer gave me the clue and following line gives the exact result in C# as like javascript. var rslt = cars.OrderByDescending(a => a, StringComparer.Ordinal); – Kevin M Aug 11 '17 at 05:54