Use own IComparer with Linq OrderBy

Your comparer looks wrong to me. You’re still just sorting in the default text ordering. Surely you want to be parsing the two numbers and sorting based on that:

public int Compare(Object stringA, Object stringB)
{
    string[] valueA = stringA.ToString().Split("https://stackoverflow.com/");
    string[] valueB = stringB.ToString().Split("https://stackoverflow.com/");

    if (valueA.Length != 2 || valueB.Length != 2)
    {
        stringA.ToString().CompareTo(stringB.ToString());
    }

    // Note: do error checking and consider i18n issues too :)
    if (valueA[0] == valueB[0]) 
    {
        return int.Parse(valueA[1]).CompareTo(int.Parse(valueB[1]));
    }
    else
    {
        return int.Parse(valueA[0]).CompareTo(int.Parse(valueB[0]));
    }
}

(Note that this doesn’t sit well with your question stating that you’ve debugged through and verified that Compare is returning the right value – but I’m afraid I suspect human error on that front.)

Additionally, Sven’s right – changing the value of items doesn’t change your bound list at all. You should add:

this.Items = items;

at the bottom of your method.

Leave a Comment