OrderbyDescending on date不按预期排序

时间:2016-08-10 18:50:21

标签: c# asp.net asp.net-mvc entity-framework linq

我设计的NotificationViewModel以下:

public class NotificationViewModel
{
    public string NotificationText { get; set; }
    public DateTime Moment { get; set; }
    public string Icon { get; set; }
}

我正在生成我的通知数据,如下所示:

List<NotificationViewModel> model = new List<NotificationViewModel>();
int days = DateTime.Now.DayOfWeek - DayOfWeek.Sunday;
DateTime weekStart = DateTime.Now.AddDays(-days);
DateTime weekEnd = weekStart.AddDays(6);

var purchases = await context.tbl1.Where(x => x.created_date <= weekEnd && x.created_date >= weekStart)
                .Select(x => new NotificationViewModel()
                {
                      Icon = "fa fa-gbp",
                      Moment = x.created_date,
                      NotificationText = "A new purchase.",
                }).ToListAsync();
model.AddRange(purchases);

var stocks = await context.tbl2.Where(x => x.created_date <= weekEnd && x.created_date >= weekStart)
               .Select(x => new NotificationViewModel()
               {
                      Icon = "fa fa-cubes",
                      Moment = x.created_date,
                      NotificationText = "A new stock",
               }).ToListAsync();
model.AddRange(stocks);
var sales = await context.tbl3.Where(x => x.created_date <= weekEnd && x.created_date >= weekStart)
               .Select(x => new NotificationViewModel()
               {
                      Icon = "fa fa-shopping-cart",
                      Moment = x.created_date,
                      NotificationText = "A new sale",
                }).ToListAsync();
model.AddRange(sales);

model.OrderByDescending(x => x.Moment); 

//The above line does not order items according to their occurrence

我也尝试过如下:

model.OrderByDescending(c=> c.Moment.Date)
.ThenBy(c=> c.Moment.TimeOfDay);

但即使这样也行不通,模型保持不变。我将如何使用这些数据进行排序?任何见解都非常感谢..

1 个答案:

答案 0 :(得分:9)

因为方法OrderByDescending返回一个新序列,而不是就地排序序列。所以你需要:

model = model.OrderByDescending(x => x.Moment).ToList(); 

或者,您可以使用以下方式对列表进行排序:

model.Sort((x, y) => y.Moment.CompareTo(y.Moment));

值得注意的是,基于文档,OrderByOrderByDescending是稳定的排序方法(如果两个项具有相同的排序顺序,则保留序列中的原始顺序),而{{{ 1}}方法被记录为不稳定的Sort。