Ordering in Linq to Entities Multiple Columns

c# entity-framework linq-to-entities

Question

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);
1
6
12/6/2012 2:42:32 PM

Accepted Answer

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);
16
12/6/2012 2:49:03 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow