Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case sensitive sorting with capitals last

Tags:

c#

sorting

I want to sort a List< string> case sensitive with capitals last, i.e. in the order

a,aBC,b,bXY,c,A,Ax,B,C,...

I have tried

Comparison<string> c = (string x1,string x2) => StringComparer.Ordinal.Compare(x1,x2);
list.Sort(c);

but it returns

A,Ax,B,C,a,aBC,b,bXY,c,...

Is there any predefined method to do this, or will I need to fiddle something together myself?

Edit: Since "capitals last" seems difficult enough I have spared numbers for the moment.

like image 454
oliver Avatar asked Mar 08 '18 07:03

oliver


1 Answers

Finally I have opted for the suggestion by @JohnTortugo. Thanks John, incredibly simple idea, short and easy to implement!

  1. Swap upper and lower case in a string by XOR'ing 0x20 with each byte (ASCII coding assumed):

    static string swapUpperLower(string s)
    {
        return System.Text.Encoding.ASCII.GetString(System.Text.Encoding.ASCII.GetBytes(s).Select(c => (byte)(c^0x20)).ToArray());
    }
    
  2. Swap case for every string in the list before and after sorting

        Comparison<string> c = (string x1,string x2) => StringComparer.Ordinal.Compare(x1,x2);
    
        sl = sl.Select(s => swapUpperLower(s)).ToList();
        sl.Sort(c);
        sl = sl.Select(s => swapUpperLower(s)).ToList();
    

Result:

a aBC b bXY c A Ax B C

like image 103
oliver Avatar answered Sep 24 '22 02:09

oliver