LINQ to SQL的 - 日期时间格式 - YYYY-MMM(2009年3月) [英] Linq to Sql - DateTime Format - YYYY-MMM (2009-Mar)
问题描述
我想写一个LINQ to SQL查询,通过用户名和日期时间做了计数和组。我想要的DateTime被格式化像下面的YYYY-MMM(即2009年3月)。
I want to write a Linq to Sql query that does a count and groups by a Username and DateTime. I want the DateTime to be formatted like following "YYYY-MMM" (i.e. 2009-Mar).
我想这会工作,但LINQ到SQL无法解析。的ToString格式的说法。
I thought this would work but Linq to Sql can't parse the ToString "format" argument.
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);
没有人有任何想法/建议?
Does anyone have any thoughts/suggestions?
感谢。
推荐答案
我不知道你不应该这样做长的方式...
I wonder if you shouldn't do that the "long" way...
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(...)
。
If you need the format as a string, do that later at the UI. Either by reconstructing a DateTime
etc, or using CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(...)
.
这篇关于LINQ to SQL的 - 日期时间格式 - YYYY-MMM(2009年3月)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!