Ahmed
Ahmed

Reputation: 11393

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

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?

Upvotes: 25

Views: 58326

Answers (4)

Simon
Simon

Reputation: 31

Turn it to ticks will work as well:

return query.OrderByDescending(c=> c.Time.Ticks)

Upvotes: 3

Richard Schneider
Richard Schneider

Reputation: 35477

Use the Date and TimeOfDay properties for the sort.

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

Upvotes: 61

Nasmi Sabeer
Nasmi Sabeer

Reputation: 1380

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)

Upvotes: 5

thmshd
thmshd

Reputation: 5847

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 :)

Upvotes: 18

Related Questions