具有分组和条件结果的linq查询

时间:2017-05-15 07:48:39

标签: linq

我之前提出过类似的问题。我有一个结构如下的车型列表:

class Car
    {
        public string Make { get; set; }
        public string Model { get; set; }
        public string SecondHand { 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", SecondHand ="N", AccidentCount = 1 ,MaintenanceCount = 0},
new Car(){Make = "Mercedes", Model = "E-200", SecondHand ="N", AccidentCount = 1 ,MaintenanceCount = 1},
new Car(){Make = "Mercedes", Model = "E-200", SecondHand ="Y", AccidentCount = 1 ,MaintenanceCount = 1},
new Car(){Make = "Mercedes", Model = "E-180", SecondHand ="N", AccidentCount = 0 ,MaintenanceCount = 1},
new Car(){Make = "Mercedes", Model = "E-180", SecondHand ="N", AccidentCount = 1 ,MaintenanceCount = 1} 
};

我在查询输出中需要的是Make和Model的2列,通过对它们进行分组,得到2列中的AccidentCount和MaintenanceCount的总和,最后如果给定模型输出“Y”有任何“SecondHand”值“Y” “否则”N“。

上面的输出应该是:

Make      Model  AccidentCount  MaintenanceCount SecondHand  
Mercedes  E-200  3              2                Y 
Mercedes  E-180  1              2                N

1 个答案:

答案 0 :(得分:0)

  

我在查询输出中需要的是通过对它们进行分组的2列Make和Model,

cars.GroupBy(c=> new {c.Make,c.Model})
  

获取2列

中的AccidentCount和MaintenanceCount之和
AccidentCount = g.Sum(c=>c.AccidentCount),
MaintenanceCount = g.Sum(c=>c.MaintenanceCount)
  

最后如果有任何&#34; SecondHand&#34;值&#34; Y&#34;对于给定的模型输出&#34; Y&#34;否则&#34; N&#34;。

SecondHand = g.Any(c=> c.SecondHand=="Y") ? "Y" : "N"

最终查询如下所示:

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),
              SecondHand = g.Any(c=> c.SecondHand=="Y") ? "Y" : "N"
              });