Is there a LINQ query that will give me the sum of several maximum values?
I've got a table of transaction data for several locations and I need to find the sum of each location's maximum from a subset of locations. So imagine the follo开发者_开发知识库wing table:
location year transactions
123 2009 57
124 2009 23
125 2009 45
123 2010 64
124 2010 12
125 2010 66
So if I'm looking just for the data for locations 123 and 124 the code should pick out the value 64 for location 123 in 2010 and 23 for location 124 in 2009.
I've got the following code which works in that it finds the maximum value for each location and then adds it to the running total.
int total = 0;
foreach (var location in locationIds)
{
int? temp = transactions.Where(t => t.Location == location)
.Max(t => t.Transactions);
if (temp.HasValue)
{
total += temp.Value;
}
}
Is there a more elegant way of coding this?
I'm using the naming you used in the table in your example above. Judging from your code, you may need to change some of the names accordingly...but I can't be positive:
var locationsToInclude = new List<int> { 123, 124 };
var sum = transaction
.Where(t => locationsToInclude.Contains(t.location))
.GroupBy(t => t.location)
.Sum(g => g.Max(t => t.transactions));
This works over all locations. I only want to get the values for a subset.
Then how about this small modification to Justin's answer?
var sum = transaction
.GroupBy(x => x.Location)
.Where(g => locationIds.Contains(g.Key))
.Sum(g => g.Max(x => x.Transactions));
精彩评论