首页 > 解决方案 > 基于时间戳的对象组列表

问题描述

具有以下界面:

public class foo
{
    [Key]
    public int Id { get; set; }}
    public string Notes { get; set; }
    public DateTime? Timestamp { get; set; }
}

使用数据上下文,例如:await context.foos.ToListAsync()返回完整的条目列表。我想要实现的目标是来自以下相同响应的重组 JSON 对象:

[
    {
        year: YYYY,
        count: 0, // <- total `foos` in year
        months: [
            {
                month: 'January',
                count: 0, // <- total `foos` in month
                days: [
                    {
                        day: 0,
                        count: 0, // <- total `foos` in day
                        foos: [
                            {
                                Id: 0,
                                Notes: '...',
                                Timestamp: '...'
                            }
                        ]
                    }
                ]
            }
        ]
    }
]

我能够通过多个嵌套的 for 循环来实现这一点。然而,这似乎是一种非常糟糕的方法,因为嵌套循环会以指数方式增加处理时间。

有没有可能用 LINQ 实现这一点的方法?或者也许是更有效的解决方案?

标签: c#linqasp.net-core-webapi

解决方案


从算法上讲,这与您使用的语言无关,您可以按照以下伪代码的行做一些事情:

for (item in listOfItems) {
    year = getYearFromItem(item)
    month = getMonthFromItem(item)
    day = gteDayFromItem(item)

    updateYears(data, year)
    updateMonth(data, month)
    updateDay(data, day)
}

您将只检查一次数据并在进行时创建year/month/day子对象。


推荐阅读