我尝试使用以下代码对几个字段进行分组:
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 });
不幸的是,最后一行代码给了我错误,因为它无法识别这三个字段。
'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?)
所有三个字段(品牌、型号、年份)均出现相同的错误。
有什么想法可以解决这个问题吗?
最佳答案
按品牌和型号对汽车进行分组后,序列中的每个元素都是一个组。您可以使用 Key
属性获取组的 key ,这样您就可以找到该组的 Make
和 Model
,但是 Year
没有任何意义...每个组中都会有多辆车,并且它们的年份都可能不同。当然,您可以使用组内的信息。例如:
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) });
但从根本上来说,您需要考虑这样一个事实:序列中的每个元素都是一个组,而不是一辆汽车。
关于c# - GroupBy 和 Select 扩展方法帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22695334/