tags:

views:

33

answers:

2

I have a linq expression that returns transactions in groups. Each transaction has a numerical value and I now need to know what is the highest value from all the transactions returned. This value is held in a field called TransactionId

Here is the expression I am using to get the grouped list.

            var transactions = ctx.MyTransactions
                               .Where (x => x.AdapterId == Id)
                               .GroupBy(x => x.DeviceTypeId);

I now need to write an expression that works on the “transactions” grouped list to find the “max” of the TransactionId field. I’ve tried different ideas but none seem to work with the grouped results. I’m new to linq so I’m not sure how to do this.

A: 

Have you tried finding the maximum in each group and then finding the maximum of that over all groups?

int max = transactions.Max(g => g.Max(t => t.TransactionId));

Or you could just query the database again:

int max = ctx.MyTransactions
             .Where(x => x.AdapterId == Id)
             .Max(t => t.TransactionId);
Mark Byers
A: 

This will give you the max in each group

var transactionIds = ctx.MyTransactions
        .Where (x => x.AdapterId == Id)
        .GroupBy(x => x.DeviceTypeId, 
                 g => new {
                    DeviceTypeId = g.Key, 
                    MaxTransaction = g.Max(x => x.TransactionId)
                });
SLaks