问题
I'm getting list of products from a database, each of them have populated paymentDate and I would like to format my data like this (just an example):
{
Week:1,
Month:8,
Total:50
},
{
Week:2,
Month:8,
Total:40
},
{
Week:3,
Month:8,
Total:70
},
{
Week:4,
Month:8,
Total:85
}
... and so on..
Now I'm getting my data grouped by month and for 4 months it returns 4 INSTEAD OF 16 rows like:
Month:8,
Total:250
And that's what I don't want..
Here's my code:
First I'm getting all rows from a last 4 months from a database, there is like 20-30 rows with PaymentDate
value (which are rows from last 4 months).
var yas = await _context.products
.AsNoTracking()
.Where(x => (x.PaymentDate != null && x.PaymentDate > DateTime.UtcNow.AddMonths(-4))).ToListAsync();
After I get all rows, I'm trying to group them on a way to get data grouped by WEEKS in each MONTH.
var grouped = yas.GroupBy(x => CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(x.PaymentDate ?? DateTime.UtcNow, CalendarWeekRule.FirstDay, DayOfWeek.Monday))
.Select(product => new ProductsDemoData
{
//Week = should be week
Amount = product.Sum(x => x.Amount),
Month = product.FirstOrDefault().PaymentDate.Value.Month
});
Example of data:
回答1:
you've grouped by Week, so you can just do this I think:
.Select(product => new ProductsDemoData
{
Week = product.Key,
Amount = product.Sum(x => x.Amount),
Month = product.FirstOrDefault().PaymentDate.Value.Month
});
来源:https://stackoverflow.com/questions/58010938/groupby-week-month