我有一个LINQ声明(EF核心3.1),我想按时间戳列的年份和月份分组,例如"2020-03“。
var result = _context.Messages
.Where(x => x.timestamp != null)
.GroupBy(x => x.timestamp.Value.Year.ToString()+"-" + x.timestamp.Value.Month.ToString())
.Select(x => new { date = x.Key, count = x.Count() })问题是数据的结果格式是"2020-3“,这就导致了以后的排序问题。
如何设置月份字符串的格式,使其始终具有带前导零的2位数字?
我读了很多关于SqlFunctions的文章--但EF中没有这些内容。还有别的办法吗?
发布于 2020-05-15 09:07:20
您可以按实际年份/月进行分组,然后投影出这些值。这样,分组就完全在SQL中完成了。一旦您拥有了内存中的集合,您就可以再次与D2 format specifer一起创建排序键。
var result = _context.Messages
.Where(x => x.timestamp != null)
.GroupBy(x => new {
x.timestamp.Value.Year,
x.timestamp.Value.Month
})
.Select(x => new {
Year = x.Key.Year,
Month = x.Key.Month,
Count = x.Count()
})
.AsEnumerable()
.Select(x => new {
Date = $"{x.Year:D2}-{x.Month:D2}",
Count = x.Count
})
.ToList();发布于 2020-05-15 08:45:00
您可以使用值为“ToString()”的d2方法的格式重载。这样,格式将确保始终得到两位数字:
x.timestamp.Value.Month.ToString("d2")https://stackoverflow.com/questions/61814974
复制相似问题