在linq中选择365天以上的数据

本文关键字:数据 365天 linq 选择 | 更新日期: 2023-09-27 17:49:36

这是我的表结构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的记录

在linq中选择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();