Home > Back-end >  How do i sort a treeview in c# alphabetically but if it begins with W put that on top
How do i sort a treeview in c# alphabetically but if it begins with W put that on top

Time:12-14

Here is my code. I am using the sort method on the treeview but it sorts alphabetically, i want it to put any nodes beginning with w on top

       public int Compare(object thisObj, object otherObj)
        {
            TreeNode thisNode = thisObj as TreeNode;
            TreeNode otherNode = otherObj as TreeNode;

            if (!thisNode.Name.Contains("Working") && !thisNode.Name.Contains("Working"))
            {
                return thisNode.Name.CompareTo(otherNode.Text);
            }

            return 0;
        }

I have tried the custom node sorter above and using the sort method

CodePudding user response:

When comparing it is important to remember the following:

return -1: this object is before the other
return 0: this object is in the same position as the other
return 1: this object is after the other

In your case the following logic should work:

If both names start with W or both names do not start with W, use CompareTo.
If only this name starts with W, return -1
If only the other name starts with W, return 1

  • Related