-2

I would like to sort an array of chars according to their ordinal positions (code points) in Unicode table.

I see that the following code works:

char[] charArray = new[] { 'h', 'e', 'l', 'l', 'o' };
Array.Sort(charArray, StringComparer.Ordinal);

But it looks a bit weird. First because both of these parameters are non-generic, and secondly, here I am using a StringComparer to compare chars.

Is this guaranteed to work? Any reference?

mk33
  • 351
  • 1
  • 2
  • 6
  • 2
    `StringComparer` in given example just offload comparison to `IComparable.CompareTo` ([source](http://referencesource.microsoft.com/#mscorlib/system/stringcomparer.cs,91)). You can as well use default comparer. – user4003407 Feb 07 '16 at 21:00
  • @PetSerAl wow what a badly designed API. StringComparer should *fail* if invoked with non-strings. – usr Feb 07 '16 at 22:56
  • 2
    So I guess the answer is: This works but don't do that. – usr Feb 07 '16 at 22:57
  • Ok, but then, what is the proper way to sort an array of characters according to their ordinal (Unicode code point number)? `.OrderBy(chr => chr)`? `Array.Sort(charArray)`? – mk33 Feb 08 '16 at 13:26

1 Answers1

2

OrderBy(chr => chr) does the trick. char is IComparable and that comparable definition compares the integer/"ordinal" value of the chars.

usr
  • 168,620
  • 35
  • 240
  • 369