Home > Software engineering >  LINQ: how to get 1 month records
LINQ: how to get 1 month records

Time:12-16

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

CodePudding user response:

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

CodePudding user response:

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