在EF Core Linq GroupBy语句中格式化日期,并在前面加零。

问题描述 投票:1回答:2

我有一个LINQ语句(EF Core 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 Core中是不可用的。有其他方法吗?

c# linq linq-to-sql ef-core-3.1
2个回答
2
投票

你可以按照实际的年月进行分组,然后投影出这些值。这样分组就完全在SQL中完成了。一旦你有了内存中的集合,你可以再次投射创建你的排序键以及 D2 格式说明者

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();

1
投票

您可以使用格式超载的 ToString() 方法,值为 "d2"。这样的格式将确保你总是得到两个数字。

x.timestamp.Value.Month.ToString("d2")
© www.soinside.com 2019 - 2024. All rights reserved.