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!

2 Years
Discussion Span
Last Post by tinstaafl

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]);

Edited by tinstaafl

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.