具有分组和条件结果的linq查询 [英] linq query with grouping and conditional result

查看:105
本文介绍了具有分组和条件结果的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

推荐答案

我需要在查询输出中通过分组将Make和Model分为2列,

What i need in output of query is 2 columns for Make and Model by grouping them,

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

在2列中获取AccidentCount和MaintenanceCount的总和

get sum of AccidentCount and MaintenanceCount in 2 columns

AccidentCount = g.Sum(c=>c.AccidentCount),
MaintenanceCount = g.Sum(c=>c.MaintenanceCount)

最后,对于给定的模型输出,如果有"SecondHand"值"Y",则输出"Y",否则为"N".

and finally if there is any "SecondHand" value"Y" for a given Model output "Y" otherwise "N".

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查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆