WPF Listbox Collection custom sort

1.4k views Asked by At

I have a listbox

DropPrice
MyPrice
Price1
Price2

I want to sort it like this

Price1
Price2
DropPrice
MyPrice

I mean, if there's an item that starts with the sequence "price", it gets priority, else the smallest string should get the priority.

My source code:

var lcv = (ListCollectionView)(CollectionViewSource.GetDefaultView(_itemsSource));
var customSort = new PrioritySorting("price");
lcv.CustomSort = customSort;

internal class PrioritySorting : IComparer
    {
        private string _text;
        public PrioritySorting(string text)
        {
            _text = text;
        }

        public int Compare(object x, object y)
        {
           //my sorting code here

        }
    }

How can i write compare method. I know, that it can return 1,0 or -1. How can i set priorities.

2

There are 2 answers

4
thomasb On BEST ANSWER

You just have to check if it starts with "price".

Note that I don't think that ToString() is appropriate; you should rather implement IComparer<T> and strongly type your objects in your listbox.

public int Compare(object x, object y)
{
    // test for equality
    if (x.ToString() == y.ToString())
    {
        return 0;
    }

    // if x is "price" but not y, x goes above
    if (x.ToString().StartsWith("Price") && !y.ToString().StartsWith("Price"))
    {
        return -1;
    }

    // if y is "price" but not x, y goes above
    if (!x.ToString().StartsWith("Price") && y.ToString().StartsWith("Price"))
    {
        return 1;
    }

    // otherwise, compare normally (this way PriceXXX are also compared among themselves)
    return string.Compare(x.ToString(), y.ToString());
}
2
Bathineni On

Here is sample code snippet for IComparer.

private class sortYearAscendingHelper : IComparer
{
   int IComparer.Compare(object a, object b)
   {
      car c1=(car)a;
      car c2=(car)b;
      if (c1.year > c2.year)
         return 1;
      if (c1.year < c2.year)
         return -1;
      else
         return 0;
   }
}

This is more specific to your Question

 internal class PrioritySorting : IComparer
    {
        private string _text;
        public PrioritySorting(string text)
        {
            _text = text;
        }

        public int Compare(object x, object y)
        {
            var str1 = x as string;
            var str2 = y as string;

            if (str1.StartsWith("price") )
            {
                if (str2.StartsWith("price"))
                    return 0;
                return 1;
            }

            return -1;
        }
    }