Sort a char array case-insensitively

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Paul E Collins

    Sort a char array case-insensitively

    char[] c = { 'a', 'b', 'c', 'A', 'B', 'C' };
    Array.Sort(c, CaseInsensitive Comparer.Defaul t);

    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.


  • Jeroen Mostert

    #2
    Re: Sort a char array case-insensitively

    Paul E Collins wrote:
    char[] c = { 'a', 'b', 'c', 'A', 'B', 'C' };
    Array.Sort(c, CaseInsensitive Comparer.Defaul t);
    >
    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?
    >
    CaseInsensitive Comparer 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<Ttha t lifts its arguments to strings:

    Array.Sort(c, (a, b) =string.Compare (a.ToString(), b.ToString(),
    StringCompariso n.CurrentCultur eIgnoreCase));

    There may be a more elegant way.

    --
    J.

    Comment

    • =?ISO-8859-1?Q?G=F6ran_Andersson?=

      #3
      Re: Sort a char array case-insensitively

      Paul E Collins wrote:
      char[] c = { 'a', 'b', 'c', 'A', 'B', 'C' };
      Array.Sort(c, CaseInsensitive Comparer.Defaul t);
      >
      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 CaseInsensetive Comparer compares strings, and if you use it
      to compare something different, it will fallback to using
      Comparer.Defaul t.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
      _____
      Göran Anderssons privata hemsida.

      Comment

      Working...