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 (mas 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?
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 (mas 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?
Share Improve this question edited Nov 12, 2020 at 21:50 ruffin 17.5k11 gold badges96 silver badges149 bronze badges asked Aug 11, 2017 at 5:06 Kevin MKevin M 5,5064 gold badges46 silver badges46 bronze badges 1- stackoverflow./questions/5430016/… – user93 Commented Aug 11, 2017 at 5:13
2 Answers
Reset to default 6Try changing the StringComparer:
Array.Sort(cars, StringComparer.Ordinal);
Array.Reverse(cars);
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);