C# – String comparison to consider numbers

csortingtreeviewwinforms

I am trying to sort nodes of a treeview with respect to their text property of course. The problem is that my comparison class does not care about numbers. Here is the code:

public class TreeNodeSorter : IComparer
{
    public int Compare(object x, object y)
    {
        var tx = x as TreeNode;
        var ty = y as TreeNode;

        return string.Compare(tx.Text, ty.Text);
    }
}

And here is the result:

enter image description here

The first child node (Debug…) is ok, but my problem is why on earth "HBM\D10" is sorted before "HBM\D7" and so on…

Best Answer

If portability is not an issue, you can p/invoke StrCmpLogicalW(). This function is used by the Windows shell to sort the file names it displays:

public class TreeNodeSorter : IComparer
{
    [DllImport("shlwapi.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
    static extern int StrCmpLogicalW(string x, string y);

    public int Compare(object x, object y)
    {
        var tx = x as TreeNode;
        var ty = y as TreeNode;

        return StrCmpLogicalW(tx.Text, ty.Text);
    }
}