Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String comparison to consider numbers

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...

like image 591
Saeid Yazdani Avatar asked Jul 11 '12 10:07

Saeid Yazdani


People also ask

Can you compare a string to a number?

Strings can't equal to numbers even if the look the same. We first need to convert the string to an int and only then will they be equal.

How do you compare a number in a string and an integer?

If you want to compare their string values, then you should convert the integer to string before comparing (i.e. using String. valueOf() method). If you compare as integer values, then 5 is less than "123". If you compare as string values, then 5 is greater than "123".

What is the best way to compare strings?

The right way of comparing String in Java is to either use equals(), equalsIgnoreCase(), or compareTo() method. You should use equals() method to check if two String contains exactly same characters in same order. It returns true if two String are equal or false if unequal.


1 Answers

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);
    }
}
like image 121
Frédéric Hamidi Avatar answered Nov 11 '22 15:11

Frédéric Hamidi