【问题标题】:Group and Count in Entity Framework实体框架中的分组和计数
【发布时间】:2012-10-22 13:26:41
【问题描述】:

我有一张包含日志的表格,我每天计算的日志如下:

// Count logs by day
IList<DataModel> models = _context.Logs
  .Where(x => x.Created >= dateMinimum && x.Created <= dateMaximum)
  .GroupBy(x => new { Year = x.Created.Year, Month = x.Created.Month, Day = x.Created.Day })
  .Select(x => new { Year = x.Key.Year, Month = x.Key.Month, Day = x.Key.Day, Count = x.Count() })
  .AsEnumerable()
  .Select(x => new DataModel { Date = new DateTime(x.Year, x.Month, x.Day), LogsCount = x.Count })
  .ToList();

// Fill empty days with dates which contains all days in range
models.AddRange(dates.Where(x => !models.Any(y => y.Date == x.Date)).Select(x => new DataModel { Date = x, LogsCount = 0 }));

如果我想独立于类型按天计算所有日志,这是可行的。

但我想按天计算日志并输入类型(错误、警告、信息...)。

我尝试将 x.Type 添加到组,但最后我只得到 3 个项目。

目前我的数据模型如下:

public class DataModel
{
    public DateTime Date { get; set; }
    public Int32 LogsCount { get; set; }
}

但也许应该是这样的:

public class DataModel
{
    public DateTime Date { get; set; }
    public KeyValuePair<String, Int32> LogsCount { get; set; }
}

其中 LogsCount 有一个包含 Type 的字符串和包含计数的 Int32。

我该怎么做?

【问题讨论】:

    标签: c# entity-framework linq-to-entities count


    【解决方案1】:

    可能要考虑使用entity functions 按日期分组。

    例子:

    var results = query.GroupBy(r => new
    {
        SentDate = System.Data.Objects.EntityFunctions.TruncateTime(r.Launch.EmailDeliveredDate),
        EventSubTypeID = r.EmailEventSubtypeID
    })
    .Select(x => new
    {
        x.Key.SentDate,
        x.Key.EventSubTypeID,
        NumResults = x.Count()
    })
    .ToList();
    

    【讨论】:

      【解决方案2】:

      你尝试过这样的事情吗?

      IList<DataModel> models = Logs
        .Where(x => x.Created >= dateMinimum && x.Created <= dateMaximum)
        .GroupBy(x => new { Year = x.Created.Year, Month = x.Created.Month, Day = x.Created.Day, Type = x.Type })
        .Select(x => new { Year = x.Key.Year, Month = x.Key.Month, Day = x.Key.Day, Count = x.Count(), Type = x.Key.Type })
        .AsEnumerable()
        .Select(x => new DataModel { Date = new DateTime(x.Year, x.Month, x.Day), LogsCount = x.Count, Type = x.Type })
        .ToList()
      
      
      public class DataModel
      {
          public DateTime Date { get; set; }
          public Int32 LogsCount { get; set; }
          public string Type { get; set; }
      }
      

      【讨论】:

      • 是的,这是我的第一个方法。它有效。但是如何填充三种类型中缺失的日期会让人感到困惑......我只是不确定这是否是最好的方法......你将如何填充每种类型中的空日期并添加 count = 0。就像我愿意。
      • 我可能会在foreach 循环中执行此操作,跨越根据this answer 生成的日期列表。对于每个日期,如果该值不存在,则添加它。我确信它可以在 LINQ 中完成,但这不是 我会 这样做的方式。如果您愿意,我可以尝试提供 LINQ 表单。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-01
      相关资源
      最近更新 更多