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.
Finally I have opted for the suggestion by @JohnTortugo. Thanks John, incredibly simple idea, short and easy to implement!
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());
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With