Member Avatar


I have searched for a while now and havn't found an answer. Would anyone happen to know how to sort first by letter then number? I have a linq expression which I need to order in this way. Ex. it currently shows up like 01, 02, 03, A1, A2, C1. But I want it to show up like, A1, A2, C1, 01, 02, 03. Would anyone happen to know how to accomplish this? Thanks!

First you'll need a custom comparer, something like this:

public class CustomComparer : IComparer<char>
    public int Compare(char x, char y)
        //If the leading characters are both letters or both digits
        //then sort normally
        if ((char.IsLetter(x) && char.IsLetter(y)) || (char.IsDigit(x) && char.IsDigit(y)))
            return x.CompareTo(y);
        //If they aren't the same then reverse the sort order
        return y.CompareTo(x);

Then use it like this:

string[] testarr = { "A2", "B1", "02", "01", "A1", "B2" };
var testarrsorted = testarr.OrderBy(x => x[0], new CustomComparer()).ThenBy(x => x[1]);