LINQ sorting special characters first?

.net, c#, linq, sorting

Solution

One of the less-well-known features of .Net 3.5 is that you can substitue a lambda for an IComparer. This is handy for cases like this where you want a one-off sort. If this isn't a one-off, you're probably better off with a custom IComparer class. Here's how you'd do this brute force style:

List<string> list = new List<string>();
list.Sort((x, y) =>
{
    if(Char.IsLetterOrDigit(x[0])){
        if(!Char.IsLetterOrDigit(y[0])){
            // x is a letter/digit and y is not, override regular CompareTo
            return -1;
        }
    }
    else if (Char.IsLetterOrDigit(y[0]))
    {
        // y is a letter/digit and x is not, override regular CompareTo
        return 1;
    }
    return x.CompareTo(y);
});

Problem

It looks like special characters are not being regarded when sorting with LINQ and I didn't expect it to. Anyway, I need to sort special characters so they appear first in a list. Any ideas? I know I can do something like: Use LINQ for arbitrary sorting, but how do I allow the sort to extend pass the special characters: Example List: - "Test" - Test Daniel

Original source