我是 LINQ to SQL 的新手,我想知道如何在 LINQ 中实现类似的功能:
Month Hires Terminations
Jan 5 7
Feb 8 8
Marc 8 5
到目前为止我已经得到了这个,我认为它有问题,但我不确定:
from term1 in HRSystemDB.Terminations
group term1 by new { term1.TerminationDate.Month, term1.TerminationDate.Year } into grpTerm
select new HiresVsTerminationsQuery
{
Date = Criteria.Period,
TerminationsCount = grpTerm.Count(term => term.TerminationDate.Month == Criteria.Period.Value.Month),
HiresCount = (from emp in HRSystemDB.Persons.OfType<Employee>()
group emp by new { emp.HireDate.Month, emp.HireDate.Year } into grpEmp
select grpEmp).Count(e => e.Key.Month == Criteria.Period.Value.Month)
});
提前致谢。
我不太确定在哪里Criteria.Period
值来自您的示例查询。
不过,我认为您正在尝试阅读所有可用月份的雇用和解雇(然后您可以轻松过滤它)。如果第一个表(终止)不包含某个指定月份(例如五月)的任何记录,您的查询可能会出错。然后select
根本不会以“May”作为参数来调用子句,即使您在第二个表(代表 Hires)中有一些数据,您也将无法找到它。
这可以使用以下方法优雅地解决连接法 http://msdn.microsoft.com/en-us/vbasic/bb737941.aspx(请参阅 MSDN 示例)。您可以选择所有终止和所有雇用(进入某种类型的数据结构),然后按月对所有数据进行分组:
var terms = from t in HRSystemDB.Terminations
select new { Month = t.TerminationDate.Month,
Year = term1.TerminationDate.Year,
IsHire = false };
var hires = from emp in HRSystemDB.Persons.OfType<Employee>()
select new { Month = emp.HireDate.Month,
Year = emp.HireDate.Year
IsHire = true };
// Now we can merge the two inputs into one
var summary = terms.Concat(hires);
// And group the data using month or year
var res = from s in summary
group s by new { s.Year, s.Month } into g
select new { Period = g.Key,
Hires = g.Count(info => info.IsHire),
Terminations = g.Count(info => !info.IsHire) }
现在查看代码时,我很确定有一些更短的方法可以编写此代码。另一方面,这段代码应该具有很好的可读性,这是一个好处。另请注意,我们将代码拆分为几个子查询并不重要。由于 LINQ to SQL 的延迟评估,这应该作为单个查询执行。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)