1

Im using MEF and executing a task which needs to be grouped with aggregate functions only when it returns more than 1 record. I need both the Max of the start hour and the min of the end hour grouped into a single record like my sql would result in on the restuled task

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

Here is the SQL that gets me basiccally what I need when more than 1 record returned

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

So when more than 1 I can filter it further but not sure how to achieve max and min?

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

}

Thanks

2 Answers 2

1

From your SQL, this should be close:

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)});

...although I'm not sure why you are grouping when you are restricting the state id column (group key). The following should also suffice:

var result = context.OperatingHours
                    .Where(oh => oh.StateId == 'CA')
                    .Select(oh => new {MaxStart = oh.Max(x => x.ComplianceHourStart),
                                       MinEnd = oh.Min(x => x.ComplianceHourEnd)});
Sign up to request clarification or add additional context in comments.

Comments

1

Something like this should do it:

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) 
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.