c# - 基于时间戳的对象组列表
问题描述
具有以下界面:
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 实现这一点的方法?或者也许是更有效的解决方案?
解决方案
从算法上讲,这与您使用的语言无关,您可以按照以下伪代码的行做一些事情:
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
子对象。
推荐阅读
- shell - 在 Shell 脚本中执行并存储结果
- r - 向数据框添加一列,跳过粘贴 -
- mysql - 如何从 mysql 查询中获取数据结果以及查询返回的行数?
- php - 使用 Google Maps API 生成随机地址
- angular - 使用验证器创建自定义 FormControl
- reporting-services - 通过 ODBC 连接在 SSRS 中调用 Oracle 存储过程
- html - 如何在 html 代码中显示“您的广告”图像?(对于网站)
- angular - 角材料单选按钮样式不起作用
- python - python - 如何从python列表中调用具有某些关键字的特定元素?
- c# - 在 C# 应用程序中使用 Azure REST API 显示没有响应