GroupBy week/month

做~自己de王妃 提交于 2020-01-06 08:22:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!