如何根据周数将空对象添加到列表中 [英] How can I add to my list empty objects based on week number
问题描述
我正在这样从数据库获取数据:
I'm getting data from db like this:
稍后我将它们分组,使其看起来像
Later I group them so it looks like
Month 6
Week 2
Amount 228
以此类推.
这是代码:
var yas = await _context.product
.AsNoTracking()
.Where(x => (x.PaymentDate != null && x.PaymentDate > DateTime.UtcNow.AddMonths(-4))).ToListAsync();
var grouped = yas.GroupBy(x => CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(x.PaymentDate ?? DateTime.UtcNow, CalendarWeekRule.FirstDay, DayOfWeek.Monday))
.Select(product => new productsDemoObject
{
Week = GetWeekNumberOfMonth(product.FirstOrDefault().PaymentDate.Value),
Amount = product.Sum(x => x.Amount),
Month = product.FirstOrDefault().PaymentDate.Value.Month
});
如您所见,第6个月只有第2周的数据.它可以按预期进行分组和工作,但是现在我想知道如何为缺失的周添加数量为0的空对象.
As you can see for Month 6 there is only data for week 2. And it's group and work as expected, but now I'm wondering how could I add empty object with amount of 0 for missing weeks.
例如,如果只有第2周,则为第1,3和4周添加数量为0的数据.
For example if there is only week 2, lets add data with amount 0 for week 1,3 and 4.
在第8个月的示例中,因为存在第2周和第3周,所以我应将第1周和第4周的金额加为0.
In example of Month 8, because there are weeks 2 and 3 I should add week 1 and 4 with amount of 0.
我怎么能做到这一点?
谢谢大家
欢呼
推荐答案
如果您想在每年的一周中输入一个条目,则需要以某种方式创建这些条目.您可以查看此答案,并根据需要对其进行一些修改.
If you want an entry per week of the year, you need to create these somehow. You could take a look at this answer and modify it a bit according to your requirements.
类似这样的东西:
DateTime jan1 = new DateTime(DateTime.Today.Year, 1, 1);
//beware different cultures, see other answers
DateTime startOfFirstWeek = jan1.AddDays(1 - (int)(jan1.DayOfWeek));
Dictionary<int, productsDemoObject> allWeeks =
Enumerable
.Range(0, 54)
.Select(i => new {
weekStart = startOfFirstWeek.AddDays(i * 7)
})
.TakeWhile(x => x.weekStart.Year <= jan1.Year)
.Select(x => new {
x.weekStart,
weekFinish = x.weekStart.AddDays(4)
})
.SkipWhile(x => x.weekFinish < jan1.AddDays(1))
.Select((x, i) => new productsDemoObject
{
Week = i + 1,
Month = x.weekStart.Month,
Amount = 0
})
.ToDictionary(x => x.Week, x => x);
foreach(var week in yas
.GroupBy(x => CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(x.PaymentDate ?? DateTime.UtcNow, CalendarWeekRule.FirstDay, DayOfWeek.Monday)))
{
allWeeks[week.Key].Amount = week.Sum(x => x.Amount);
}
这篇关于如何根据周数将空对象添加到列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!