我有一个包含日志的表格,我按如下方式计算每天的日志:
// 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 有一个包含类型的字符串和包含计数的 Int32。
我该怎么做?
最佳答案
可能要考虑使用 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();
关于c# - Entity Framework 中的分组和计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13012472/