L.Z.
L.Z.

Reputation: 11

How to sort an array of chars alphabetically so that the uppercase and the lowercase version of the same letter are next to each other?

For example

Input array: 'a', 'b', 'B', 'A'

Output with Array.Sort(): 'A', 'B', 'a', 'b'

Desired output: 'A', 'a', 'B', 'b'

I understand why 'A' is considered lower than 'a', but I want it to be sorted alphabetically, not by the corresponding integers of the characters.

Is there a Comparer class that would solve the problem as a second argument for Array.Sort() ?

Upvotes: 0

Views: 1081

Answers (2)

NetMage
NetMage

Reputation: 26917

You can use LINQ to create a new char Array with the right order:

var ans = chars.OrderBy(Char.ToUpper).ThenBy(c => c).ToArray();

Upvotes: 0

Eric Lippert
Eric Lippert

Reputation: 660138

Is there a Comparer class that would solve the problem as a second argument for Array.Sort() ?

For strings, you want to use OrdinalIgnoreCase or InvariantCultureIgnoreCase, depending on whether you care about culture sensitivity or not. See:

Which is generally best to use -- StringComparison.OrdinalIgnoreCase or StringComparison.InvariantCultureIgnoreCase?

For chars, I do not know of a built-in comparer that does that, but it is easy to write your own. See

What is the correct way to compare char ignoring case?

Note that Array.Sort is a mutating sort; if you want a non-mutating sort, then do an OrderBy on ToUpper or ToUpperInvariant. Note that there are pitfalls here; see

How to sort an array of chars alphabetically so that the uppercase and the lowercase version of the same letter are next to each other?

Note also that it is unclear whether your intention is that A and a be equal -- in which case A, a, A would be a legal ordering, since equal things are equal, or whether you still want an ordering within a and A. Again, be careful. If that's what you want then you'll have to do a ThenBy also.

Upvotes: 5

Related Questions