Gur*_*Rao -2 c# linq asp.net asp.net-mvc entity-framework
我有以下NotificationViewModel设计:
public class NotificationViewModel
{
public string NotificationText { get; set; }
public DateTime Moment { get; set; }
public string Icon { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我正在生成我的通知数据,如下所示:
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
Run Code Online (Sandbox Code Playgroud)
我也试过如下:
model.OrderByDescending(c=> c.Moment.Date)
.ThenBy(c=> c.Moment.TimeOfDay);
Run Code Online (Sandbox Code Playgroud)
但即使这样也行不通,模型保持不变.我将如何对这些数据进行排序?任何见解都非常感谢..
因为该方法OrderByDescending返回一个新序列,并且不按顺序对序列进行排序.所以你需要:
model = model.OrderByDescending(x => x.Moment).ToList();
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用以下方式对列表进行排序:
model.Sort((x, y) => y.Moment.CompareTo(y.Moment));
Run Code Online (Sandbox Code Playgroud)
值得注意的是,基于文档,OrderBy并且OrderByDescending是稳定的排序方法(如果两个项具有相等的排序顺序,则保留序列中的原始顺序),而该Sort方法被记录为不稳定的排序.
| 归档时间: |
|
| 查看次数: |
788 次 |
| 最近记录: |