Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordering in Linq to Entities Multiple Columns

I have a table in SQL Server that has the following columns

  • ID (Identity/Primary Key)
  • DestinationID (Foreign key)
  • Date (Date Field)
  • Time (Time Field)
  • DayOfWeek (Char(3) Field) i.e. "MON","TUE" etc..

I want to order the data by Date and Time, then by DayOfWeek and Time. So all the records with dates appear at the top, and ordered by time, then the DayOfWeek order by time.

I have tried several ways but just cant get my head around it, I have the following code

    var qry = ctx.DestinationTimings.Where(x => x.DestinationID == this.ID)
                     .OrderBy(t => t.Date).ThenBy(t => t.Date != null)
                     .ThenBy(t => SqlFunctions.CharIndex(t.DayOfWeek + ",", "MON,TUE,WED,THU,FRI,SAT,SUN"))
                     .ThenBy(t => t.Time);
like image 947
Valeklosse Avatar asked Dec 06 '12 14:12

Valeklosse


1 Answers

If Date is nullable you could do something like this:

var qry = ctx.DestinationTimings.Where(x => x.DestinationID == this.ID)
                 .OrderBy(t => t.Date ?? DateTime.MaxValue)
                 .ThenBy(t => SqlFunctions.CharIndex(t.DayOfWeek + ",", "MON,TUE,WED,THU,FRI,SAT,SUN"))
                 .ThenBy(t => t.Time);
like image 125
dzavala Avatar answered Sep 28 '22 05:09

dzavala