gpt4 book ai didi

c# - LINQ 按月分组问题

转载 作者:太空狗 更新时间:2023-10-29 22:35:09 25 4
gpt4 key购买 nike

我是 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 值来自何处。

但是我认为您正在尝试阅读所有可用月份的雇用和终止(然后您可以轻松地过滤它)。如果第一个表 (Termination) 不包含某个指定月份(比如 5 月)的任何记录,您的查询可能会出错。然后 select 子句根本不会以“May”作为参数调用,即使您在第二个表(代表 Hires)中有一些数据,您也无法找到

这可以使用 Concat method 优雅地解决(参见 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 的惰性评估,这应该作为单个查询执行。

关于c# - LINQ 按月分组问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2105208/

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