Lasselito Lasselito - 3 months ago 11
C# Question

Sorting list after Date then time

So I'm working on a website ( MVC ) that handles Schedule entries for bands during a festival and I need to present bookings in a logical order and I´m having some unexpected difficulties when I try to order them. My goal is to order them first by date and then by time.

I've obviously read all similar questions that I could find but none seems to solve the problem.

This is my model (The parts that matter in this situation):

public int ScheduleEntryId { get; set; }
public int ScheduleId { get; set; }
public int? BandId { get; set; }
public int? MovieId { get; set; }
public int? TechnicianId { get; set; }
public DateTime? StartTime { get; set; }
public DateTime? EndTime { get; set; }
public DateTime EventDate { get; set; }


I´m trying to get a sorted list of entries from a specific Band. So this is what I have at the moment:

List<ScheduleEntry> scheduleEntries =
db.ScheduleEntries.Where(x => x.BandId == band.BandId)
.OrderBy(x => x.EventDate)
.ThenBy(z => z.StartTime.Value).ToList();


This does sort the entries after the date, but not after time.

I have also tried to seperate the linq and sorting so that I can use .TimeOfDay, since linq does not support that method. This is what I tried:

var scheduleEntries = db.ScheduleEntries.Where(x => x.BandId == band.BandId).ToList();
scheduleEntries.OrderByDescending(z => z.EventDate.Date).ThenBy(z=> z.StartTime.Value.TimeOfDay);


I know this is pretty silly and I´m probably missing something obvious, but I just cant get it to work properly. Help would be greatly appreciated.

Answer

Try

List<ScheduleEntry> scheduleEntries = db.ScheduleEntries
  .Where(x => x.BandId == band.BandId)
  .OrderBy(x => x.EventDate)
  .ThenBy(z => z.StartTime)
  .ToList();

Edited As per @IvanStoev's suggestion in the comments

Comments