IComparer for integers and force empty strings to end

Posted by paulio on Stack Overflow See other posts from Stack Overflow or by paulio
Published on 2010-04-06T13:21:42Z Indexed on 2010/04/06 13:33 UTC
Read the original article Hit count: 249

Filed under:

Hi,

I've written the following IComparer but I need some help. I'm trying to sort a list of numbers but some of the numbers may not have been filled in. I want these numbers to be sent to the end of the list at all times.. for example...

[EMPTY], 1, [EMPTY], 3, 2

would become...

1, 2, 3, [EMPTY], [EMPTY]

and reversed this would become...

3, 2, 1, [EMPTY], [EMPTY]

Any ideas?

        public int Compare(ListViewItem x, ListViewItem y)
    {
        int comparison = int.MinValue;
        ListViewItem.ListViewSubItem itemOne = x.SubItems[subItemIndex];
        ListViewItem.ListViewSubItem itemTwo = y.SubItems[subItemIndex];

        if (!string.IsNullOrEmpty(itemOne.Text) && !string.IsNullOrEmpty(itemTwo.Text))
        {
            uint itemOneComparison = uint.Parse(itemOne.Text);
            uint itemTwoComparison = uint.Parse(itemTwo.Text);

            comparison = itemOneComparison.CompareTo(itemTwoComparison);
        }
        else
        {
            // ALWAYS SEND TO BOTTOM/END OF LIST.
        }

        // Calculate correct return value based on object comparison.
        if (OrderOfSort == SortOrder.Descending)
        {
            // Descending sort is selected, return negative result of compare operation.
            comparison = (-comparison);
        }
        else if (OrderOfSort == SortOrder.None)
        {
            // Return '0' to indicate they are equal.
            comparison = 0;
        }

        return comparison;
    }

Cheers.

© Stack Overflow or respective owner

Related posts about c#