简体   繁体   English

LINQ:如何获得 1 个月的记录

[英]LINQ: how to get 1 month records

The following query is returning a number of daily orders.以下查询返回一些每日订单。 I want to create another query that will return int number of orders in one month .我想创建另一个查询,它将在一个月内返回int订单数。 The problem is some months have 29days, some 30 or 31. Any help is appreciated!问题是有些月份有 29 天,有些是 30 或 31 天。感谢您的帮助!

public int GetNewDailyOrders()
{
    return _DbContext.Carts.Where(x => x.Created >= DateTime.UtcNow.AddDays(-1)).Count();
}
public int GetMonthlyOrders(int month, int year)
{

    return _DbContext.Carts.Count(x => x.Created.Year == year && x.Created.Month == month);
}

may be, you should consider support different timezones, summertime or not, something like this as well可能是,你应该考虑支持不同的时区,夏令时与否,类似这样的东西

My chief complaint with the accepted answer is that it manipulates table data, which generally kills the db's ability to use indexes我对已接受答案的主要抱怨是它操纵表数据,这通常会破坏数据库使用索引的能力

Consider instead working out the date range and querying it instead:考虑改为计算日期范围并查询它:

var n = DateTime.Now;
var f = new DateTime(n.Year, n.Month, 1);
var t = new DateTime(n.Year, n.Month + 1, 1);

_dbContext.Carts.Count(c => c.CreatedDate >= f && c.CreatedDate < t);

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

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