开发者

c# case sensitive ASCII sort?

开发者 https://www.devze.com 2023-02-08 16:41 出处:网络
i need to sort an string Array and it MUST be sorted by ascii. if using Array.Sort(myArray), it won\'t work.

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


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

Array.Sort(myArray, StringComparer.Ordinal);


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消