Linq查询给出数据透视表类的结果

时间:2017-05-13 13:04:35

标签: c# linq datatable

我有一个有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}
};

查询结果应为:     

        
  • 制作Model AccidentCount MaintenanceCount
  •     
  • Mercedes E-200 3 2
  •     
  • Mercedes E-180 1 2

1 个答案:

答案 0 :(得分:1)

使用LINQ并按MakeModel对您的汽车进行分组。现在,您可以总结AccidentCountMaintenanceCount

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)
        });