В моей системе у меня есть таблица с историей веса участников (ParticipantData):
ParticipantId Weight Date
1 86 2020-01-30
1 83 2020-02-03
2 98 2020-01-20
2 96 2020-01-26
3 75 2020-02-06
Мне нужно получить сумму весов, но участник должен только посчитать один раз с последним весом до или равный указанному c date.
Вот что у меня есть:
DateTime dt = DateTime.Now;
DateTime? chartStartDate = new DateTime(Event.Event.StartDateTime.Value.Year, Event.Event.StartDateTime.Value.Month, Event.Event.StartDateTime.Value.Day);
DateTime? chartEndDate = dt < Event.Event.EndDateTime ? dt : Event.Event.EndDateTime;
bool chartLoop = true;
if (chartStartDate < dt) {
// Get all weights
var participantsWeightStats = await _context.ParticipantData.ToListAsync();
// Loop date with steps of 7
do {
// Get the sum of `participantsWeightStats` before or equal to the loop-date
// In the following I need to Distinct/GroupBy ParticipantId so every participant only counts with the latest weight
var chartData = participantsWeightStats.Where(x => x.Date <= chartStartDate).OrderByDescending(x => x.Date).ToList();
ViewData["PData_Values"] += chartData.Sum(x => x.Weight).ToString().Replace(".", "").Replace(",", ".") + ",";
ViewData["PData_Labels"] += "'" + chartStartDate.Value.ToString("d") + "',";
chartStartDate = chartStartDate.Value.AddDays(7);
if (chartStartDate > chartEndDate && chartLoop) {
chartStartDate = chartEndDate;
chartLoop = false;
}
} while (chartStartDate <= chartEndDate);
}
Я пробовал разные подходы с GroupBy и Distinct, но безуспешно.