I am trying to GroupBy a few fields using the following code:
var cars = tmp.Select(a => new { a.Make, a.Model, a.Year });
cars = cars.Distinct()
.OrderBy(a => a.Make)
.ThenBy(a => a.Model);
var groupedCars = cars.GroupBy(a => new { a.Make, a.Model })
.Select(b => new { b.Make, b.Model, b.Year });
Unfortunately, the very last line of code is giving me errors as is does not recognize the three fields.
'System.Linq.IGrouping(AnonymousType#1,AnonymousType#2)' does not contain a definition for 'Make' and no extension method 'Make' accepting a first argument of type 'System.Linq.IGrouping(AnonymousType#1,AnonymousType#2)' could be found (are you missing a using directive or an assembly reference?)
It is the same error for all three fields (Make, Model, Year).
Any ideas how to fix this?
Once you've grouped the cars by make and model, each element of the sequence is a group. You can get the key for the group with the Key
property, so you can find the group's Make
and Model
, but Year
makes no sense... there will be multiple cars in each group, and they could all have different years. You can use the information within the group, of course. For example:
var groupedCars = cars.GroupBy(a => new { a.Make, a.Model })
.Select(g => new { g.Key.Make, g.Key.Model,
MinYear = g.Min(car => car.Year),
MaxYear = g.Max(car => car.Year) });
But fundamentally you need to be thinking about the fact that each element of the sequence is a group, not a single car.
See more on this question at Stackoverflow