c# – Linq to Sql – 日期时间格式 – YYYY-MMM(2009年3月)

我想编写一个Linq to Sql查询,它通过Username和DateTime进行计数和分组.我希望DateTime的格式如下“YYYY-MMM”(即2009年3月).
我认为这会工作,但Linq to Sql无法解析ToString“format”参数.
dc.MyTable
.GroupBy(r => new
{
Name = r.UserName,
YearMonth = r.SomeDateTime.ToString("yyyy-MMM")
})
.Select(r => new
{
Name = r.UserName,
YearMonth = r.YearMonth,
Count = r.Count()
})
.OrderBy(r => r.YearMonth)
.ThenBy(r => r.Name);
有没有人有任何想法/建议?
谢谢.
解决方法:
我想知道你是不是应该这样做“漫长”的方式……
dc.MyTable
.GroupBy(r => new
{
Name = r.UserName,
Year = r.SomeDateTime.Year,
Month = r.SomeDateTime.Month
})
.Select(r => new
{
Name = r.UserName,
Year = r.Year,
Month = r.Month,
Count = r.Count()
})
.OrderBy(r => r.Year)
.ThenBy(r => r.Month)
.ThenBy(r => r.Name);
如果您需要格式为字符串,请稍后在UI处执行此操作.通过重建DateTime等,或使用CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(…).