Search code examples
.neticomparer

Can't create Comparer


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?


Solution

  • 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.