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

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

本文介绍了具有分组和条件结果的linq查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了我之前问过的类似问题外,我还有一个补充.我有以下类型的汽车类型列表:

I have an addition to a similar question I have asked before. I have a list of car type structured like below :

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的总和,最后对于给定的Model输出"Y"是否存在任何"SecondHand"值"Y" 否则为N".

What i need in output of query is 2 columns for Make and Model by grouping them, get sum of AccidentCount and MaintenanceCount in 2 columns and finally if there is any "SecondHand" value"Y" for a given Model output "Y" otherwise "N".

以上的输出应为:


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

推荐答案

cars.GroupBy(c=> new {c.Make,c.Model})
AccidentCount = g.Sum(c=>c.AccidentCount),
MaintenanceCount = g.Sum(c=>c.MaintenanceCount)
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"
              });

这篇关于具有分组和条件结果的linq查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 22:17