Navyseal
Navyseal

Reputation: 901

Selecting top two of the combined group by linq

I am trying to figure out how to pick the last two "Transactions" from my query.

My Query looks like this

var summary= (from tType in _context.CommandCentre.TransactionTypes
    join tSummary in _context.CommandCentre.TransSummary on tType.Id equals tSummary.TransactionType
    where tSummary.ChargeFlag.ToLower() == ChargeFlag.Overcharge.ToString().ToLower()
    group tSummary by new { tType.Name, tSummary.NumberOfTransactions, tSummary.PeriodDate }
    into gResult
    select new
    {
        Fee = gResult.Key.Name,
        TransactionCount = gResult.Key.NumberOfTransactions,
        Period = gResult.Key.PeriodDate,
        ActualAmount = gResult.Sum(x => x.ActualAmount),
    }).OrderByDescending(x=>x.Period);

Now if I do a Take(2) I get only the last two records, while I want to get the last two records for every "Fee" of my selection. Basically Two records for every "Fee" ordered by "Period" date.

not sure how to do this in a single query.

Upvotes: 2

Views: 115

Answers (1)

Maverick
Maverick

Reputation: 801

Try this :

var result = summary.GroupBy(p => p.Fee)
                    .SelectMany(d => d.OrderBy(r => r.Period).Take(2))
                    .ToList();

Upvotes: 3

Related Questions