LINQ Group By x-number of days

Viewed 303

I have a list of objects List<StatisticsData>

   public class StatisticsData
{
    public Guid Id { get; set; }
    public string Name { get; set; }    
    public DateTime EndTime { get; set; }
}

Sample values:

22-02-2020 | StatisticsData 
21-02-2020 | StatisticsData 
20-02-2020 | StatisticsData
19-02-2020 | StatisticsData 
19-02-2020 | StatisticsData 
18-02-2020 | StatisticsData
17-02-2020 | StatisticsData 
16-02-2020 | StatisticsData 
15-02-2020 | StatisticsData

My goal is to divide it into batches for X days. For example, if I want to take entries for 2 days, in result I will recieve:

First batch:

 22-02-2020 | StatisticsData 
 21-02-2020 | StatisticsData 

Second batch:

 20-02-2020 | StatisticsData
 19-02-2020 | StatisticsData 
 19-02-2020 | StatisticsData 

Third batch:

 18-02-2020 | StatisticsData
 17-02-2020 | StatisticsData 

Etc...

I am stuck to make it with LINQ..

3 Answers

Decide on some "epoch" where the two-day slots will start (e.g. DateTime.MinValue to avoid ever worrying about negative values), and then group by slot index:

var batches = data.GroupBy(stat => (int) (stat.EndTime - DateTime.MinValue).TotalDays / 2);

Other possible solution is that by using Ticks as follow:

long batchPeriod = (TimeSpan.TicksPerDay * 2);
var batches = data.GroupBy(g => g.EndTime.Ticks % batchPeriod);

Try group by index:

var list = Enumerable.Range(40,25);
var groupByRecords = 10;
var groupedList = list
    .Select((x, i) => new { value = x, index = i })
    .GroupBy( x=> x.index / groupByRecords)
    .Select(x => x.Select(y => y.value));

Edited: will not work if multiple entries per day, sorry.

Related