이것은 특히 강력하지는 않지만 일부 리팩터링과 관련이있을 수 있지만 자신의 논리에 맞게 확장 할 수있는 출발점을 제공 할 수 있습니다. 열거로
귀하의 상태 :
public enum Status
{
CheckIn,
CheckOut,
Lunch
}
다음의 목록에 데이터를 돌려
:
public class EmployeeStatusChange
{
public int EmployeeId { get; set; }
public DateTime DateTime { get; set; }
public Status Status { get; set; }
}
그리고이 확장 방법을 사용하십시오
public static double CalculateHours(this List<EmployeeStatusChange> changes)
{
changes = changes.OrderBy(x => x.DateTime).ToList();
double hours = 0;
var start = DateTime.MinValue;
var lunch = DateTime.MinValue;
var checkedOut = false;
foreach (var change in changes)
{
// exclude anything before the first check in, or if we have already checked out
if ((start == DateTime.MinValue && change.Status != Status.CheckIn) || checkedOut)
{
continue;
}
// Set the start time
if (start == DateTime.MinValue && change.Status == Status.CheckIn)
{
start = change.DateTime;
continue;
}
switch (change.Status)
{
case Status.CheckIn:
if (lunch == DateTime.MinValue)
{
continue;
}
start = change.DateTime;
continue;
case Status.Lunch:
lunch = change.DateTime;
hours += (change.DateTime - start).TotalHours;
break;
case Status.CheckOut:
checkedOut = true;
hours += (change.DateTime - start).TotalHours;
break;
}
}
return hours;
}
이 돌아갑니다 6.5 :
var items = new List<EmployeeStatusChange>();
items.Add(new EmployeeStatusChange { EmployeeId = 1, Status = Status.CheckIn, DateTime = new DateTime(2015, 1, 1, 9, 0, 0) });
items.Add(new EmployeeStatusChange { EmployeeId = 1, Status = Status.Lunch, DateTime = new DateTime(2015, 1, 1, 10, 30, 0) });
items.Add(new EmployeeStatusChange { EmployeeId = 1, Status = Status.CheckIn, DateTime = new DateTime(2015, 1, 1, 11, 0, 0) });
items.Add(new EmployeeStatusChange { EmployeeId = 1, Status = Status.Lunch, DateTime = new DateTime(2015, 1, 1, 12, 0, 0) });
items.Add(new EmployeeStatusChange { EmployeeId = 1, Status = Status.CheckIn, DateTime = new DateTime(2015, 1, 1, 13, 0, 0) });
items.Add(new EmployeeStatusChange { EmployeeId = 1, Status = Status.CheckOut, DateTime = new DateTime(2015, 1, 1, 17, 0, 0) });
items.CalculateHours();