1

我正在使用 MEF 并执行一项任务,该任务仅在返回超过 1 条记录时才需要使用聚合函数进行分组。我需要将开始时间的最大值和结束时间的最小值组合成一条记录,就像我的 sql 会导致重新处理的任务一样

var ohs = await Bl.UoW.Repositories.OperatingHours
    .FindInDataSourceAsync(oh => ((oh.ProductId == productTypeId 
        && oh.StateId == state) 
        || (oh.StateId == complianceHours.State)));

当返回超过 1 条记录时,这是我基本上需要的 SQL

SELECT 
    StateId,
    MAX(ComplianceHourStart),
    MIN(ComplianceHourEnd)
FROM 
    OperatingHours 
GROUP BY
    StateId
HAVING 
    StateId = 'CA'

因此,当超过 1 时,我可以进一步过滤它但不确定如何达到最大值和最小值?

if (ohs != null && ohs.Count() > 1)
{
    //
    ohs = ohs.GroupBy(x => x.State).Max(x => x.ComplianceHourStart?...

}

谢谢

4

2 回答 2

1

这样的事情应该这样做:

ohs = ohs.GroupBy(x => x.State)
    .Select(g => new 
    { 
        //You need to make a choice on StateId, here... First one?
        StateId = g.First().StateId, 
        MaxComplianceHourStart = g.Max(o => o.ComplianceHourStart),
        MinComplianceHourEnd = g.Min(o => o.ComplianceHourEnd) 
    });
于 2013-09-24T23:12:56.453 回答
1

从您的 SQL 来看,这应该很接近:

var result = context.OperatingHours
                    .GroupBy(oh => oh.StateId)
                    .Select(oh => new {StateId = oh.Key, 
                                       MaxStart = oh.Max(x => x.ComplianceHourStart),
                                       MinEnd = oh.Min(x => x.ComplianceHourEnd)});

...虽然我不确定在限制状态 id 列(组键)时为什么要分组。以下内容也应该足够了:

var result = context.OperatingHours
                    .Where(oh => oh.StateId == 'CA')
                    .Select(oh => new {MaxStart = oh.Max(x => x.ComplianceHourStart),
                                       MinEnd = oh.Min(x => x.ComplianceHourEnd)});
于 2013-09-24T23:13:12.783 回答