【问题标题】:Filling DateTime and Int gaps填补 DateTime 和 Int 空白
【发布时间】:2012-03-29 17:48:11
【问题描述】:

我正在使用 EF 按月、按天或按小时计算帖子。

我最终得到了一个 DateTime/Int 列表,其中存在一些 DateTime 间隔。

间隔是年,按年计算,按月计算,按月计算,...

有没有办法编写一个按年或月填补 DateTime 空白的扩展,...

或者甚至是另一个填补 int 空白的扩展?

谢谢你, 米格尔

【问题讨论】:

    标签: entity-framework list datetime


    【解决方案1】:

    在不查看代码的情况下,为什么不使用计数为 0 的所有所需日期(即没有间隔)预先填充表格。

    Date     Count
    Jan2012  0
    Feb2012  0
    Mar2012  0
    ...
    Dec2049  0
    

    这将保证您的列表永远不会有空白。您可以使用 sql 日期函数编写此生成脚本或使用 Excel 并导入数据库。

    【讨论】:

    • 这可能看起来很老套,但我会使用这个解决方案。很简单。
    【解决方案2】:

    基本上我在做的事情如下:

    // Tupple to hold data
    IList<Tuple<DateTime, Int32>> data = new List<Tuple<DateTime, Int32>>();
    
    // Get data from repository (Count by year) and add to Tupple
    _repository.Set<Post>()
    .Where(x => x.Created >= start && x.Created <= end)
    .GroupBy(x => new { Year = x.Created.Year })
    .Select(x => new { Year = x.Key.Year, Count = x.Count() })
    .ToList().ForEach(x => data.Add(new Tuple<DateTime, Int32>(new DateTime(x.Year, 1, 1), x.Count)));
    
    // Fill empty years with 0 as count
    for (Int32 i = 0; i <= (end - start).TotalYears; i++)
      if (!data.Any(x => x.Item1 == start.AddYears(i)))
        data.Add(new Tuple<DateTime, Int32>(start.AddYears(i), 0));
    
    // Resort data
    data = data.OrderBy(x => x.Item1).ToList();
    

    基本上我一直在寻找一种以更少步骤完成此任务的方法......

    也许使用表 Union 或 Join ...

    我只是填写我正在使用的许多步骤...

    谢谢你, 米格尔

    【讨论】:

      猜你喜欢
      • 2015-08-19
      • 2017-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多