我有一个有4个属性的类。我想通过对2个字段进行分组并计算2个其他数字字段来获取此对象列表中的结果表。我无法做到这一点,我们将不胜感激任何帮助:
class Car
{
public string Make { get; set; }
public string Model { get; set; }
public int AccidentCount { get; set; }
public int MaintenanceCount { get; set; }
}
List<Car> cars = new List<Car>()
{
new Car(){Make = "Mercedes", Model = "E-200", AccidentCount = 1 ,MaintenanceCount = 0},
new Car(){Make = "Mercedes", Model = "E-200", AccidentCount = 1 ,MaintenanceCount = 1},
new Car(){Make = "Mercedes", Model = "E-200", AccidentCount = 1 ,MaintenanceCount = 1},
new Car(){Make = "Mercedes", Model = "E-180", AccidentCount = 0 ,MaintenanceCount = 1},
new Car(){Make = "Mercedes", Model = "E-180", AccidentCount = 1 ,MaintenanceCount = 1}
};
查询结果应为:
答案 0 :(得分:1)
使用LINQ并按Make
和Model
对您的汽车进行分组。现在,您可以总结AccidentCount
和MaintenanceCount
:
IEnumerable<Car> summedUp = cars.GroupBy(c => new { c.Make, c.Model })
.Select(g => new Car()
{
Make = g.Key.Make,
Model = g.Key.Model,
AccidentCount = g.Sum(c => c.AccidentCount),
MaintenanceCount = g.Sum(c => c.MaintenanceCount)
});