Linq OrderByDescending with two columns with zero dates

I have a table with two datetime zero columns, ETA and ETD. There is always value. I want to order a table by date. So, for example, if the ETA is null, use an ETD to order. If the ETD is null, use ETA; if both values ​​are not null, use ETA (as always).

I have it:

var route = db.RouteJourney.Where(j => j.JourneyId == id).OrderByDescending(j => j.ETA ?? j.ETD); 

I also tried this (which is the same):

 var route = db.RouteJourney.Where(j => j.JourneyId == id).OrderByDescending(j => j.ETA.HasValue ? j.ETA : j.ETD); 

Am I missing something? My little brain says that if the ETA is null, use an ETD and then order it, but it does not give the correct result.

Any help is appreciated.

EDIT

I get with this:

If RouteJourney - [Name, RouteId (Key), JourneyId, ETA, ETD]

and values:

[Stop A, 1, 1, null, 10/03/13], [Stop B, 4, 1, 12/03/13, 13/03/13], [Stop C, 2, 1, 14/03 / 13, null], [Stop D, 3, 1, 16/03/13, null]

Ordered as follows:

Stop C Stop B Stop A Stop D

Thank...

+1
c # lambda linq
Mar 06 '13 at 12:12
source share
1 answer

Try using an anonymous type

 var route = db.RouteJourney .Where(j => j.JourneyId == id) .OrderByDescending(item => (new { DT = item.ETA.HasValue ? item.ETA : item.ETD }).DT); 

Or the pursuer in QES:

 var route = from item in db.RouteJourney where item.JourneyId == id order by (new { DT = item.ETA.HasValue ? item.ETA : item.ETD }).DT descending select item; 
+3
Mar 06 '13 at 12:36
source share



All Articles