如何获得每个月的总和?

时间:2016-11-04 11:27:01

标签: c# asp.net linq

A有一个包含9月,10月,11月的集合列表但是我想特别添加每月

scanf

我的代码

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 

我得到了所有的金额从9月到11月,我真正想要的是按月收取总和例子9月我有3个小时,10月5日,5月5个小时。

抱歉新手TIA

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

按日期列出按日期分组 然后选择所有差异的每个摘要

var grouped = oList.GroupBy(d=>StartTime.Month).Select(c=>c.Sum(d=>(d.EndTime-d.StartTime)).ToArray();