我使用此代码按年,月和employeeId对行进行分组。
var dtrSummary = from dtr in db.DTRs
group dtr by new { dtr.Date.Year, dtr.Date.Month, dtr.EmployeeId } into g
select new
{
Year = g.Key.Year,
Month = g.Key.Month,
NoOfDays = g.Count(),
FullName = db.EmployeeRates.Where(e => e.Id == g.Key.EmployeeId).Select(e => e.FullName).FirstOrDefault(),
Time1 = // Get total hours between two datetime
// DateTime timein = new DateTime(year, month, day, tihh1, timm1, 0);
// DateTime timeout = new DateTime(year, month, day, tohh1, tomm1, 0);
// Timespan totalTime1 = timeout - timein;
};
但我不知道如何使用linq group获得总时数,如上所示。
这是我的表:
+----------------------------------------------------------------------+
| Date | Timeinhh | Timeinmm | Timeouthh | Timeoutmm | EmployeeId |
+----------------------------------------------------------------------+
| 10/1/2015 | 9 | 0 | 18 | 0 | 1 |
| 10/2/2015 | 9 | 0 | 18 | 0 | 2 |
| 10/3/2015 | 9 | 0 | 18 | 0 | 1 |
| 10/4/2015 | 9 | 0 | 18 | 0 | 2 |
+----------------------------------------------------------------------+
答案 0 :(得分:1)
您可能希望在分组DTR之前计算每个小时。
var DTRs2 = db.DTRs.ToList().Select(d => new
{
Date = d.Date,
Hours = new DateTime(d.Date.Year, d.Date.Month, d.Date.Day, d.Timeouthh, d.Timeoutmm, 0)
.Subtract(new DateTime(d.Date.Year, d.Date.Month, d.Date.Day, d.Timeinhh, d.Timeinmm, 0)).TotalHours,
EmployeeId = d.EmployeeId
}).ToList();
var dtrSummary =
(from dtr in DTRs2
group dtr by new { dtr.Date.Year, dtr.Date.Month, dtr.EmployeeId } into g
select new
{
Year = g.Key.Year,
Month = g.Key.Month,
NoOfDays = g.Count(),
EmpId = g.Key.EmployeeId,
FullName = db.EmployeeRates.Where(e => e.Id == g.Key.EmployeeId).Select(e => e.FullName).FirstOrDefault(),
Time1 = g.Sum(dtr => dtr.Hours) // Get total hours between two datetime
});
我还建议定义另一个类/表,而不是每次都使用匿名类型:
public class DTRDetails
{
public DTR DTR { get; set; }
public EmployeeRate EmployeeRate { get; set; }
public string FullName
{
get { return EmployeeRate.FullName; }
}
public int Hours
{
get
{
return (int)(new DateTime(DTR.Date.Year, DTR.Date.Month, DTR.Date.Day, DTR.Timeinhh, DTR.Timeinmm, 0)
.Subtract(new DateTime(DTR.Date.Year, DTR.Date.Month, DTR.Date.Day, DTR.Timeouthh, DTR.Timeoutmm, 0))).TotalHours;
}
}
public int Hours2
{
get
{
// return something
}
}
public int Hours3
{
get { return Hours - Hours2; }
}
}