Search code examples
c#sortingculture

Best way to find string that sorts after all letters in the current culture


In C#, I am looking to have a list of names sorted alphabetically (case insensitive) in the current culture, and have a "fake name" that automatically sorts at the end of that list.

If the sort was using ASCII, we could use '{' as this is after 'z', so it'll always sort afterwards. However, this doesn't work in general for a culture based sort.

Right now I am using 'ZZZZZZZZZZZ' which works for English, but I know isn't the right answer - is there a good way of doing it?

(I'm aware that one option is to just put these to the end after sorting - unfortunately that isn't simple in this case)

        var strings = new[] {"abc", "zzz", "ZZZ", "{"};

        var sortedStrings = strings.OrderBy(x => x, StringComparer.Create(new CultureInfo("en-GB"), ignoreCase: true));

        Console.WriteLine(string.Join(",", sortedStrings));
        // gives {,abc,zzz,ZZZ

Solution

  • If i'm not wrong, the last character in utf-16 is U+10FFFD (U+10FFFE and U+10FFFF seems to be reserved) So you may do this to get a string that I think would always be the last in a sort:

    string fakeName= char.ConvertFromUtf32(0x10FFFD);