0

I have a class

public class PAUserAllowedTimesModel
{
    public List<AllowedTime> Times { get; set; }
    public List<AllowedTime> BusyTimes { get; set; }
    public DateTime SelectedDate { get; set; }
    public int DateID { get; set; }
}

I have a list of object of this class:

List<PAUserAllowedTimesModel> model = ...

I want to sort this collection by SelectedDate. I try:

public class PAUserAllowedTimesModelComparer : IComparer<ITW2012Mobile.ViewModels.PAUserAllowedTimesModel>
{
    public int Compare(ViewModels.PAUserAllowedTimesModel x, ViewModels.PAUserAllowedTimesModel y)
    {
        if (x.SelectedDate > y.SelectedDate)
            return 0;
        else
            return 1;
    }
}

and then

model.Sort(new PAUserAllowedTimesModelComparer());

but it just mix elements, not sort. What is wrong?

John
  • 727
  • 2
  • 10
  • 17

2 Answers2

5

Your comparer will never return -1, so it's violating the Compare contract...

Fortunately you can make it much simpler anyway:

public int Compare(ViewModels.PAUserAllowedTimesModel x, 
                   ViewModels.PAUserAllowedTimesModel y)
{
    // Possibly reverse this, depending on what you're trying to do
    return x.SelectedDate.CompareTo(y.SelectedDate);
}

Or using LINQ:

model = model.OrderBy(x => x.SelectedDate).ToList();

Note that this doesn't do an in-place sort, unlike List<T>.Sort.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
3

Your implementation of IComparer is wrong. You need to return 0 if the elements are equal, 1 if x > y and -1 if y > x or vice versa, depending on whether you want to sort descending or ascending.

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443