Kai
Kai

Reputation: 123

c# case sensitive ASCII sort?

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

Upvotes: 11

Views: 12857

Answers (3)

Oded
Oded

Reputation: 498992

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);

Upvotes: 2

CodesInChaos
CodesInChaos

Reputation: 108790

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.

Upvotes: 6

Chris Taylor
Chris Taylor

Reputation: 53699

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

Array.Sort(myArray, StringComparer.Ordinal);

Upvotes: 21

Related Questions