GroupBy and Select extension method assistance

时光总嘲笑我的痴心妄想 提交于 2019-12-06 14:28:37

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.

I am not going to argue with Skeet's logic for my answer is similar.

But my suggestion is to remove the Select projection which does the result selector that sums up the years. That can be done by using the GroupBy overload which does the same process.

cars.GroupBy (car => new { car.Make, car.Model }, // Key selector for make and model as keys
              vehicle => vehicle,                 // Element selector, we want all items of the original car instance which has the year
              (key, vehicle) => new               // Result selector, we want to sum up the min/max year of vehicle.
                                {
                                    Make  = key.Make,
                                    Model = key.Model,
                                    MinYear = vehicle.Min (car => car.Year),
                                    MaxYear = vehicle.Max (car => car.Year)
                                }
              );

Result looks like this:

on this data:

var cars = new List<Car>
{
    new Car() { Make="Dodge", Model="Charger", Year=2007},
    new Car() { Make="BMW",   Model="M6",      Year=2007},
    new Car() { Make="Dodge", Model="Charger", Year=2012},
    new Car() { Make="BMW",   Model="X1",      Year=2013},
    new Car() { Make="BMW",   Model="X1",      Year=2014},
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!