C# String sorting... how to compare non-Ordinal but put lowercase after uppercase for strings starting with same letter?

78 Views Asked by At

Suppose I have four strings abc, Abc, Bca, and bca. The requirement is that these would be sorted (when alphabetical) to Abc, abc, Bca, bca.

With this code:

names.Sort((a, b) => string.Compare(a, b));

It is sorted as abc, Abc, bca, Bca. If I add StringComparison.Ordinal parameter then it is sorted as Abc, Bca, abc, bca. Is there any parameter I can pass to make it return Abc, abc, Bca, bca without having to sort it an additional time?

Thanks

1

There are 1 best solutions below

0
Charlieface On BEST ANSWER

You can use a custom comparer that first sorts case-insensitively, then only if the strings are the same it sorts case-sensitive..

names.Sort((a, b) => {
    var compare = string.Compare(a, b, StringComparison.OrdinalIgnoreCase);
    if (compare != 0)
        return compare;
    compare = string.Compare(a, b, StringComparison.Ordinal);
    return compare;
});

dotnetfiddle