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:
The first child node (Debug...) is ok, but my problem is why on earth "HBM\D10" is sorted before "HBM\D7" and so on...
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.
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".
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.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With