有人可以帮助我吗,所以我想制定一种方法,该方法将从加班单中计算出该月每个星期的总时数。
readonly List<KeyValuePair<DateTime, TimeSpan>> overTimeList = new List<KeyValuePair<DateTime, TimeSpan>>();//the list of overtime hours, the data is printed below in the form of data {...}
DateTime start = new DateTime(calendar1.CurrentDate.Year, calendar1.CurrentDate.Month, 1); //start (beginning of month in calendar)
DateTime stop = new DateTime(calendar1.CurrentDate.Year, calendar1.CurrentDate.Month, 1).AddMonths(1).AddDays(-1);//end (end of calendar month)
var weeksOverTimeSum = WeeklyOverTime(start, stop); //This is how I call the method
//method in which I want to get a certain list
private List<SundayWithWeekSum> WeeklyOverTime(DateTime startDate, DateTime stopDate)
{
var w = (int)startDate.DayOfWeek - 1;
var result = from q in overTimeList
where q.Key >= startDate && q.Key <= stopDate
group q by (q.Key.Date.Day + w) / 7 into g
select new SundayWithWeekSum { Day = g.FirstOrDefault().Key, Balance = new TimeSpan(g.Sum(x => x.Value.Ticks)) };
//group q by(q.Key.Date.Day + (w == 0 ? w - 1 : w - 2)) / 7 into g
//select new SundayWithWeekSum { Day = g.FirstOrDefault().Key, Balance = new TimeSpan(g.Sum(x => x.Value.Ticks)) };
return result.ToList();
}
class SundayWithWeekSum
{
public DateTime Day { get; set; }
public TimeSpan Balance { get; set; }
}
我在日历中显示此数据,我将考虑六月,该列表是几天的加班时间,我希望整个月的overTimeList与
data {
[0]{6/3/2019, 00:12:00},
[1]{6/4/2019, -00:11:00},
[2]{6/5/2019, 00:13:00},
[3]{6/7/2019, 00:13:00},
[4]{6/8/2019, -00:14:00},
[5]{6/11/2019, -00:35:00},
[6]{6/12/2019, 00:15:00},
[7]{6/14/2019, -00:02:00},
[8]{6/15/2019, -01:20:00},
[9]{6/17/2019, 00:11:00},
[10]{6/18/2019, 00:08:00},
[11]{6/19/2019, 00:14:00},
[12]{6/21/2019, 00:14:00},
[13]{6/22/2019, -00:54:00},
[14]{6/24/2019, 00:20:00},
[15]{6/25/2019, 00:12:00},
[16]{6/26/2019, 00:12:00},
[0]{6/29/2019, 00:48:00}
}
因此,现在该在日历中显示工人的工作时间了,现在,作为该方法的输入,我指定了特定月份的开始和结束时间,然后我想计算出所有工作周的加班总数这个月。您最终获得了SundayWithWeekSum列表,例如:
FirstWeek- 06/02/2019; +00.00,
SecondWeek- 06/09/2019; 13.00,
ThirdWeek- 16/06/2019; -1.47,
FourthWeek- 06/23/2019; -00.27,
FifthWeek- 06/30/2019; 1.12
这是我的代码示例,我以为我要经历一个月,每天,并且要休息一下,直到星期日我将每周(天)的总余额保存在“ balanceForWeeks”列表中。
感谢大家的帮助。
最佳答案
这应该可以解决问题-
readonly List<KeyValuePair<DateTime, TimeSpan>> overTimeList = new List<KeyValuePair<DateTime, TimeSpan>>();
private List<SundayWithWeekSum> WeeklyOverTime(DateTime startDate, DateTime stopDate)
{
var w = (int)startDate.DayOfWeek - 1;
var result = from q in overTimeList
where q.Key >= startDate && q.Key <= stopDate
group q by (q.Key.Date.Day + w) / 7 into g
select new SundayWithWeekSum { Day = g.FirstOrDefault().Key, Balance = new TimeSpan(g.Sum(x => x.Value.Ticks)) };
return result.ToList();
}
上面的函数将返回
List<SundayWithWeekSum>
,其中周从星期日开始,一周的总时长。它包括开始和结束日期。让我知道我是否想念什么。
关于c# - 计算一周的总加类时间,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57108668/