无法创建Comparer

时间:2012-02-21 12:43:14

标签: .net icomparer

我有一个班级

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; }
}

我有这个类的对象列表:

List<PAUserAllowedTimesModel> model = ...

我想通过SelectedDate对此集合进行排序。我试试:

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;
    }
}

然后

model.Sort(new PAUserAllowedTimesModelComparer());

但它只是混合元素,而不是排序。有什么问题?

2 个答案:

答案 0 :(得分:5)

您的比较器将从不返回-1,因此违反了Compare合同......

幸运的是,无论如何你都可以让它变得更简单:

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);
}

或使用LINQ:

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

请注意,与List<T>.Sort不同,这不会执行就地排序。

答案 1 :(得分:3)

您对IComparer的实施是错误的。如果元素相等,则需要返回0;如果是x > y,则需要返回0;如果y > x,则需要返回-1,反之亦然,具体取决于您是要按降序还是按升序排序。 / p>