这是我的表结构t_physical_inventory
dte_cycle_count | qty | location
我正在使用以下Linq查询来获取结果
int number = 3;
List<t_physical_inventory> Location = (from c in dc.t_physical_inventories
where (c.dte_cycle_count == null ||
((TimeSpan)(Convert.ToDateTime(c.dte_cycle_count) -
(DateTime.Now.Date))).Days > 365)
&& (c.qty > 0)
orderby (c.location)
select c).Take(number).ToList();
问题:我无法得到那些dte_cycle_count大于365的记录
尝试:
int number = 3;
List<t_physical_inventory> Location = null;
Location = (from c in dc.t_physical_inventories
where (c.dte_cycle_count == null
|| (DateTime.Now.Date - Convert.ToDateTime(c.dte_cycle_count))
).Days > 365)
&& (c.qty > 0)
orderby (c.location)
select c).Take(number).ToList();
使用TotalDays
作为时间跨度1年12天从Days
返回12,但TotalDays
返回Years * 365 + 12
此外,您应该按照Yahya的建议从较晚的日期中减去较早的日期。
时间跨度是否为正?您可以使用Duration
-方法来获取绝对值:
List<t_physical_inventory> Location = null;
Location = (from c in dc.t_physical_inventories
where (c.dte_cycle_count == null
|| (c.dte_cycle_count.Value - DateTime.Now.Date).Duration.Days > 365)
&& (c.qty > 0)
orderby (c.location)
select c).Take(number).ToList();
然而,这样对待正时间跨度和负时间跨度是一样的。也许最好先从后面的DateTime
中减去前面的DateTime
。
请注意,如果您想要一年以上的数据,您需要使用不同的方法:
List<t_physical_inventory> Location = null;
Location = (from c in dc.t_physical_inventories
where (c.dte_cycle_count == null || c.dte_cycle_count.Value < DateTime.Now.AddYears(-1)) && (c.qty > 0)
orderby (c.location)
select c).Take(number).ToList();