Linq group by DateTime / intervals

I have the following request

 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 is a DateTime. The above smell is a little imo Is there any clean way to group by DateTimes based intervals?

Edit: I don't really like this, it is a string playing and creating a string. Ideally, I would like to create a DateTime from a group, not a string.

+3
source share
5 answers

I think I really wanted to

group t by
 new DateTime(t.Time.Year,t.Time.Month,t.Time.Day ,t.Time.Hour,t.Time.Minute,0) 
into g

None of the Add / Subtract suggestions work for me, even if I also set miliseconds to +.

dateTime.ToString ("yyyy-MM-dd HH: mm") is a good alternative to strinc concatenation if I need a string.

+10
source

sort of

group t by t.AddSeconds(60- t.Time.Seconds) // rounds to nearest minute
+1

:

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

EDIT: .AddSeconds, @Colin

0

600 000 000 , - , :

var x = from t in v
        group t by new DateTime(t.Time.Ticks - (t.Time.Ticks % 600000000)) into g
        select new { Tag = g.Key, Frequency = g.Count() };
0
source
var x = from t in v
group t by t.Time.Date.AddMinutes((Int32)t.Time.TimeOfDay.TotalMinutes) into g
   select new { Tag = g.Key, Frequency = g.Count() };
0
source

Source: https://habr.com/ru/post/1731937/