Kenneth Montealto Kenneth Montealto - 1 month ago 5
ASP.NET (C#) Question

How to get the sum of each Month?

A have a collection list that contains September ,October,November However i want to add specifically Each Month

Start Time EndTime
September 11,2016 5:00PM September 11,2016 8:00PM
September 12,2016 10:00AM September 12,2016 8:00PM
October 1,2016 5:00PM September 11,2016 8:00PM
October 2,2016 10:00AM September 12,2016 8:00PM
November 1,2016 5:00PM November 11,2016 8:00PM
November 2,2016 10:00AM November 12,2016 8:00PM


My code

List<MonthHours> oList=new List<MonthHours>();
Int total=0;
TimeSpan span=new TimeSpan();
foreach(var data in oList)
{
Span=data.EndTime-data.StartTime;
Total+=span.hours;
}


I got all the sums From september to November , What i actually want is to get the sumb By Month Example In september i got 3 hours , int october 5 hours, in November 5 hours.

Sorry newbie TIA

Answer
var result = oList
    .GroupBy(data => data.StartTime.ToString("MMMM"))
    .Select(g => new MonthHours {
        Month = g.Key,
        Total_Hours = g.Sum(d => (d.EndTime - d.StartTime).TotalHours)
    });

foreach (var month in result) {
    var str = string.Format("Month : {0}, Total Hours : {1}", month.Month, month.Total_Hours);
}