Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq to sql: Order by datetime desc, then order by the time part of the data asc?

Tags:

linq-to-sql

This is a quick one.
In Linq to sql, I need to order by a datetime field descending then order by the time part of the same datetime filed ascending, make sense? Here's an example of the result needed:

[Serial] [Date (mm-dd-yyyy:hh-MM-ss)]
1 3-13-2008:10-10-02
2 3-13-2008:10-12-60
3 3-12-2008:12-05-55


I tried :

return query.OrderByDescending(c=> c.Time).ThenBy(c=> c.Time.TimeOfDay);


And also tried:

query.OrderByDescending(c => c.Time).ThenBy(c => c.Time.Hour).ThenBy(c=> c.Time.Minute).ThenBy(c=> c.Time.Second);


but never seemed to work. Any suggestions?

like image 219
Galilyou Avatar asked Mar 28 '11 20:03

Galilyou


4 Answers

Use the Date and TimeOfDay properties for the sort.

return query
   .OrderByDescending(c=> c.Time.Date)
   .ThenBy(c=> c.Time.TimeOfDay);
like image 143
Richard Schneider Avatar answered Nov 08 '22 15:11

Richard Schneider


The Problem is that "Time" contains Date and Time information, thus, already sorting completely. You would have to take the Date Part to sort with first.

return query.OrderByDescending(c=> c.Time.Date).ThenBy(c=> c.Time.TimeOfDay);

Not tested :)

like image 20
thmshd Avatar answered Nov 08 '22 14:11

thmshd


I think first orderByDescending sorts everything by datetime(date+time), so the following orderbys will become effective only if you have any records with the same timestamp.

Try this

query.OrderByDescending(c=> c.Time.Date).ThenBy(c=> c.Time.TimeOfDay)
like image 5
Nasmi Sabeer Avatar answered Nov 08 '22 15:11

Nasmi Sabeer


Turn it to ticks will work as well:

return query.OrderByDescending(c=> c.Time.Ticks)
like image 3
Simon Avatar answered Nov 08 '22 15:11

Simon