сначала сгруппируйте данные по дате, а затем попробуйте
public class Billingdata
{
public int Price { get; set; }
public DateTime Start { get; set; }
public DateTime End { get; set; }
}
public class GroupingData {
public int Start { get; set; }
public int End { get; set; }
}
var timerangelist = new List<GroupingData> {
new GroupingData{ Start = 10, End=13 },
new GroupingData{ Start = 13, End=16 },
new GroupingData{ Start = 16, End=19 },
new GroupingData{ Start = 19, End=22 },
};
var result = new List<Billingdata>();
var billings = new List<Billingdata> {
new Billingdata{Price = 10, Start = new DateTime(2020,08,02,10,00,00), End = new DateTime(2020,08,02,11,00,00) },
new Billingdata{Price = 10, Start = new DateTime(2020,08,02,11,00,00), End = new DateTime(2020,08,02,12,00,00) },
new Billingdata{Price = 10, Start = new DateTime(2020,08,02,12,00,00), End = new DateTime(2020,08,02,13,00,00) },
new Billingdata{Price = 10, Start = new DateTime(2020,08,02,13,00,00), End = new DateTime(2020,08,02,14,00,00) },
new Billingdata{Price = 10, Start = new DateTime(2020,08,02,14,00,00), End = new DateTime(2020,08,02,15,00,00) },
new Billingdata{Price = 10, Start = new DateTime(2020,08,02,15,00,00), End = new DateTime(2020,08,02,16,00,00) },
new Billingdata{Price = 10, Start = new DateTime(2020,08,02,16,00,00), End = new DateTime(2020,08,02,17,00,00) }
};
foreach (var item in timerangelist)
{
var data = billings.Where(w => item.End >= w.End.Hour && w.Start.Hour >= item.Start).ToList();
var p = data.Sum(s => s.Price);
var ss = data.FirstOrDefault(f => f.Start.Hour == item.Start)?.Start;
var e = data.FirstOrDefault(f => f.End.Hour == item.End)?.End;
if (ss == null || e == null) { continue; }
result.Add(
new Billingdata { Price = p,
Start = (DateTime)ss,
End = (DateTime)e,
}
);
}
enter code here