Guruprasad Rao Guruprasad Rao - 3 months ago 7
C# Question

OrderbyDescending on date does not order as expected

I have below

NotificationViewModel
designed:

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


and I am generating my Notification data as below:

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


I've also tried as below:

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


But event that did not work and model remained same.. How would I go sorting with this data? Any insights is much appreciated..

Answer

Because the method OrderByDescending returns a new sequence and doesn't order the sequence in-place. So you need to :

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

Alternatively, you can sort the list in-place using:

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

It is worth noting that based on the documentation, OrderBy and OrderByDescending are stable Sort methods (Original order in the sequence is preserved if two items have an equal sort order) , while the Sort method is documented as an unstable Sort.