简体   繁体   English

按日期在不同方向排序

[英]Order by date in different directions

I have a booking system and a page showing a user's bookings - past and future. 我有一个预订系统和一个显示用户预订的页面 - 过去和未来。

I want to order the bookings with future bookings first, ordered with the next session at the top (asc), then past bookings, beginning with the latest session (desc). 我想先订购未来的预订,订购下一个会议在顶部(asc),然后通过预订,从最新会议(desc)开始。

I currently have this: 我目前有这个:

from sess in Sessions
    orderby sess.SessionDate < DateTime.Now.Date, sess.SessionDate
    select sess

But that gives both sets in asc order. 但是这给了两组asc顺序。 Any way to conditionally sort after the first order by clause? 在第一个order by子句之后有条件排序的任何方法?

I've also considered using IQueryable<T>.Concat . 我也考虑过使用IQueryable<T>.Concat Would that be the way to go? 这会是要走的路吗? I assume that results in a Union of some sort, but can I guarantee it would keep the sort order for both sets? 我认为这会产生某种联盟,但我可以保证它会保留两组的排序顺序吗?

eg results: Sessions 例如结果:会话

2015-03-01 - some class
2015-03-15 - a different class
2015-04-10 - also a class
(the split between past and future sessions)
2014-12-22 - some tutorial
2014-11-15 - some sort of class
2014-10-08 - some other class

You can use a ternary operator combined with a DateDiff function for the second order by. 您可以使用三元运算符与DateDiff函数结合使用二阶。 This will allow you to swap DateTime.Now and your SessionDate 这将允许您交换DateTime.NowSessionDate

let isSessionDateLessThanNow = sess.SessionDate < DateTime.Now
orderby isSessionDateLessThanNow, 
        isSessionDateLessThanNow ? 
           SqlFunctions.DateDiff("s", sess.SessionDate, DateTime.Now) :
           SqlFunctions.DateDiff("s", DateTime.Now, sess.SessionDate)

What about split it into two separate queries, first one with future sessions order by session date ascending. 那么将它分成两个单独的查询,第一个是会话日期升序的未来会话顺序。 add them to a list. 将它们添加到列表中。 an then another query with past sessions order by session date descending. 然后是会话日期降序的过去会话的另一个查询。 add them to the same list. 将它们添加到同一列表中。

i don't see any chance to solve this i one query without any mess. 我没有看到任何机会解决这个我一个查询没有任何混乱。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM