gpt4 book ai didi

c# - 如何获得每个月的总和?

转载 作者:行者123 更新时间:2023-11-30 16:00:17 26 4
gpt4 key购买 nike

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

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

我的代码

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

我得到了从 9 月到 11 月的所有总和,我真正想要的是按月示例获得总和在 9 月我有 3 小时,int 10 月 5 小时,11 月 5 小时。

抱歉新手TIA

最佳答案

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

关于c# - 如何获得每个月的总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40421487/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com