By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,456 Members | 1,372 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,456 IT Pros & Developers. It's quick & easy.

Sort a char array case-insensitively

P: n/a
char[] c = { 'a', 'b', 'c', 'A', 'B', 'C' };
Array.Sort(c, CaseInsensitiveComparer.Default);

After this, c is ordered { 'A', 'B', 'C', 'a', 'b', 'c' }.

I want letters to be sorted together regardless of case, e.g. 'A' next to
'a'.

Why doesn't that case-insensitive sort work? What should I do instead?

Eq.
Jul 9 '08 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Paul E Collins wrote:
char[] c = { 'a', 'b', 'c', 'A', 'B', 'C' };
Array.Sort(c, CaseInsensitiveComparer.Default);

After this, c is ordered { 'A', 'B', 'C', 'a', 'b', 'c' }.

I want letters to be sorted together regardless of case, e.g. 'A' next to
'a'.

Why doesn't that case-insensitive sort work? What should I do instead?
CaseInsensitiveComparer operates on strings only, not characters. I don't
think the framework has lexicographical comparers for characters out of the box.

The most straightforward way to achieve what you want is to use a
Comparison<Tthat lifts its arguments to strings:

Array.Sort(c, (a, b) =string.Compare(a.ToString(), b.ToString(),
StringComparison.CurrentCultureIgnoreCase));

There may be a more elegant way.

--
J.
Jul 9 '08 #2

P: n/a
Paul E Collins wrote:
char[] c = { 'a', 'b', 'c', 'A', 'B', 'C' };
Array.Sort(c, CaseInsensitiveComparer.Default);

After this, c is ordered { 'A', 'B', 'C', 'a', 'b', 'c' }.

I want letters to be sorted together regardless of case, e.g. 'A' next to
'a'.

Why doesn't that case-insensitive sort work?
Because the CaseInsensetiveComparer compares strings, and if you use it
to compare something different, it will fallback to using
Comparer.Default.Compare() instead.
What should I do instead?
You can make your own comparer that turns the characters to lower case
and compares them:

Array.Sort(c, (x, y) =char.ToLower(x) - char.ToLower(y));

or

Array.Sort(c, delegate(char x, char y) { return char.ToLower(x) -
char.ToLower(y); });

--
Göran Andersson
_____
http://www.guffa.com
Jul 9 '08 #3

This discussion thread is closed

Replies have been disabled for this discussion.