0

我有一堂课

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

但它只是混合元素,而不是排序。怎么了?

4

2 回答 2

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.

于 2012-02-21T12:44:47.997 回答
3

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

于 2012-02-21T12:44:13.740 回答