如何通过Linq中的DateTime差异订购? [英] How do I OrderBy a DateTime difference in Linq?

查看:47
本文介绍了如何通过Linq中的DateTime差异订购?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有CreatedDate列的表.我想按数据库中最长的行进行排序,但需要通过从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.

我意识到这很简单,只需按CreatedDate排序即可,但是我需要做的还不止于此.

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 they 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.

第1步)

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

第2步)

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

这将导致以下错误:

方法'System.TimeSpan Subtract(System.DateTime)'不支持SQL转换.

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

推荐答案

奇怪的是,"Subtract()"不起作用,而Minus起作用. 尝试:

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

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

(在LINQPad中使用主"数据库进行了测试)

(Tested in LINQPad using the "master" database)

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

这篇关于如何通过Linq中的DateTime差异订购?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆