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?

1

2 Answers 2

6

Try changing the StringComparer:

Array.Sort(cars, StringComparer.Ordinal);
Array.Reverse(cars);
Sign up to request clarification or add additional context in comments.

2 Comments

You are right, the following code gives the correct result in my case in C#. var rslt = cars.OrderByDescending(a => a, StringComparer.Ordinal);
And though @Rajesh deleted his answer explaining this, 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.
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);

3 Comments

It gives following different result (not like javascript) 8587009748118224023PP,8587009748118224023Po,8587009748118224023P?,8587009748118224023P<,8587009748118224023P,,8587009748118224023P$
@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);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.