views:

324

answers:

2

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: http://stackoverflow.com/questions/921107/use-linq-for-arbitrary-sorting, but how do I allow the sort to extend pass the special characters:

Example List:

  • "Test"
  • Test

Daniel

+3  A: 

System.Linq.Enumerable provides overloads of OrderBy and ThenBy that accept a comparer that implements IComparer<T>. You would just need to write your own comparer (one method) that defines how you want the strings to be ordered.

dahlbyk
+4  A: 

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);
});
Jacob Proffitt
The overload of List<T>.Sort() that accepts a Comparer<T> delegate has been around since .NET 2.0. http://msdn.microsoft.com/en-us/library/w56d4y5z%28VS.80%29.aspx This would not work for methods like OrderBy that only accept an IComparer<T>.
dahlbyk
Cool. Good to know, dahlbyk.
Jacob Proffitt
I applied this to the OrderBy method.
DDiVita