简体   繁体   中英

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 . The problem is some months have 29days, some 30 or 31. Any help is appreciated!

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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