无法创建比较器
我有一个类
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());
但它只是混合元素,而不是排序。怎么了?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的比较器将永远返回-1,因此它违反了
Compare
约定...幸运的是,无论如何您都可以使其变得更简单:
或者使用LINQ:
请注意,这不会进行就地排序,与
List.Sort
不同。Your comparer will never return -1, so it's violating the
Compare
contract...Fortunately you can make it much simpler anyway:
Or using LINQ:
Note that this doesn't do an in-place sort, unlike
List<T>.Sort
.您的
IComparer
实现是错误的。如果元素相等则需要返回0,如果x > 则返回1。如果 y > 则为 y,并且 -1 x
或反之亦然,具体取决于您要按降序还是升序排序。Your implementation of
IComparer
is wrong. You need to return 0 if the elements are equal, 1 ifx > y
and -1 ify > x
or vice versa, depending on whether you want to sort descending or ascending.