user2196615
user2196615

Reputation: 11

How to use Max and Group By in LINQ

I try to use this line:

return  ObjectContext.TH_Proposal.GroupBy.where(/* condition*/).(y => y.ProposalID).Max(y =>y.ProposalDate);

I want a result like this using LINQ

select * 
from TH_Proposal
where ProposalDate in (select max(ProposalDate)from TH_Proposal group by  ProposalID)

Upvotes: 0

Views: 104

Answers (2)

D Stanley
D Stanley

Reputation: 152634

This is much easier in Linq than SQL since Linq can take the first item of each group:

return  
    ObjectContext.TH_Proposal
                 .OrderBy(y => y.ProposalDate)
                 .GroupBy(y => y.ProposalID)
                 .Select(g => g.First());

Upvotes: 0

René Vogt
René Vogt

Reputation: 43936

You can do it like this:

ObjectContext.TH_Proposal.GroupBy(
                  p => p.ProposalID,
                  (id, g) => g.OrderByDescending(p => p.ProposalDate).First());

This groups the entries by ProposalID and selects the one with the highest ProposalDate.

Upvotes: 1

Related Questions