Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# case sensitive ASCII sort?

Tags:

c#

sorting

ascii

i need to sort an string Array and it MUST be sorted by ascii.

if using Array.Sort(myArray), it won't work.

for example: myArray is ("aAzxxxx","aabxxxx") if using Array.Sort(myArray) the result will be

  1. aabxxxx
  2. aAzxxxx

but if ascii sort, because A < a, (capital A is 65, a is 97, so A < a) the result will be

  1. aAzxxxx
  2. aabxxxx

this is the result i need. any ideas about how to ASCII sort an string Array?

thx

like image 281
Kai Avatar asked Feb 06 '11 14:02

Kai


3 Answers

If I have understood you correctly, you want to perform an Ordinal comparison.

Array.Sort(myArray, StringComparer.Ordinal);
like image 90
Chris Taylor Avatar answered Nov 10 '22 00:11

Chris Taylor


If you want a lexical sort by the char-code you can supply StringComparer.Ordinal as a comparer to Array.Sort.

Array.Sort(myArray,StringComparer.Ordinal);

The StringComparer returned by the Ordinal property performs a simple byte comparison that is independent of language. This is most appropriate when comparing strings that are generated programmatically or when comparing case-sensitive resources such as passwords.

The StringComparer class contains several different comparers from which you can choose depending on which culture or case-sensitivity you want.

like image 41
CodesInChaos Avatar answered Nov 09 '22 22:11

CodesInChaos


Use an overload of Sort that takes a suitable IComparer<T>:

Array.Sort(myArray, StringComparer.InvariantCulture);

This sort is case sensitive.

If you are looking for a sorting by the ASCII value, use StringComparer.Ordinal:

Array.Sort(myArray, StringComparer.Ordinal);
like image 22
Oded Avatar answered Nov 10 '22 00:11

Oded