我有以下查询
var x = from t in v
group t by t.Time.Year + "-" t.Time.Month + "-" +
t.Time.Day + " " t.Time.Hour + ":" + t.Time.Minute into g
select new { Tag = g.Key, Frequency = g.Count() };t.Time是一个DateTime。上面的味道有点i.m.o的味道。有没有什么干净的方法可以根据DateTimes对间隔进行分组?
编辑:我不太喜欢的是字符串的处理和字符串的生成。理想情况下,我希望从组中生成一个DateTime,而不是一个字符串。
发布于 2010-02-09 07:57:01
似乎我真正想要的是
group t by
new DateTime(t.Time.Year,t.Time.Month,t.Time.Day ,t.Time.Hour,t.Time.Minute,0)
into g涉及加/减的建议对我都不起作用,即使我也将毫秒设置为+。
如果我需要字符串,dateTime.ToString("yyyy-MM-dd HH:mm")是strinc连接的一个很好的替代方案。
发布于 2010-02-09 06:40:22
就像这样
group t by t.AddSeconds(60- t.Time.Seconds) // rounds to nearest minute发布于 2010-02-09 06:35:37
这样如何:
DateTime[] v = new DateTime[]
{
new DateTime(2010, 01, 01, 01, 01, 00, 100),
new DateTime(2010, 01, 01, 01, 01, 30, 200),
new DateTime(2010, 01, 01, 02, 01, 00, 300),
new DateTime(2010, 01, 01, 03, 01, 45, 400)
};
var x = from t in v
//group t by t.ToString("yyyy-MM-dd HH:mm") into g
group t by t.AddSeconds(-t.TimeOfDay.TotalSeconds % 60) into g
select new { Tag = g.Key, Frequency = g.Count() };编辑:根据@Colin建议更改为.AddSeconds
https://stackoverflow.com/questions/2225371
复制相似问题