Search code examples
c#winformsdata-structurestreeviewtreenode

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


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("W") && !otherNode.Name.Contains("Z"))
            {
                return thisNode.Name.CompareTo(otherNode.Text);
            }

            return 0;
        }

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


Solution

  • 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