开发者

How do I OrderBy a DateTime difference in Linq?

开发者 https://www.devze.com 2023-01-18 12:11 出处:网络
I have a table with a CreatedDate column. I want to order by the rows that have been in the database the longest, but need to determine the number of days by subtracting it from DateTime.Now.

I have a table with a CreatedDate column. I want to order by the rows that have been in the database the longest, but need to determine the number of days by subtracting it from DateTime.Now.

I realise this is doable simply by ordering by the CreatedDate, but I need to do more than that.

I need to order the items by the amount of times t开发者_开发百科hey have been used within a period of time, in effect getting the most popular items.

So what I want to do is first determine the number of days, and after that divide this by the number of times each item has been used.

Step 1)

orderby (DateTime.Now.Subtract(t.CreatedDate.Value).Days)

Step 2)

orderby (t.UsedCount/DateTime.Now.Subtract(t.CreatedDate.Value).Days)

This results in the following error:

Method 'System.TimeSpan Subtract(System.DateTime)' has no supported translation to SQL.


Oddly, "Subtract()" doesn't work, but Minus does. try:

 orderby (t.UsedCount/(DateTime.Now - t.CreatedDate.Value).Days)

(Tested in LINQPad using the "master" database)

from sp in Spt_monitors
orderby sp.Io_busy / (DateTime.Now - sp.Lastrun).Days
select sp
0

精彩评论

暂无评论...
验证码 换一张
取 消