简体   繁体   English

C#LINQ Group by

[英]C# LINQ Group by

I'm new to C# and trying to answer some LINQ questions. 我是C#的新手并试图回答一些LINQ问题。 I'm stuck on 1st marked as difficult... 我坚持第一次标记为难...

Q: What were the top 10 origin airports with the largest average​ departure delays, including the values of these delays? 问:平均出发延误最多的十大起源机场是什么,包括这些延误的价值? (Hint: use group by)? (提示:使用分组)?

I have a list named "Flights" populated with more than 20000 objects of class "FlightInfo". 我有一个名为“Flights”的列表,其中包含超过20000个 “FlightInfo”的对象。

Properties of the FlightInfo class are: string Carrier, string Origin, string Destination, int DepartureDelay, int ArrivalDelay, int Cancelled, int Distance . FlightInfo类的属性包括: string Carrier,string Origin,string Destination,int DepartureDelay,int ArrivalDelay,int Cancelled,int Distance

I understand that I should group FlightInfo by FlightInfo.Origin and than average each of these groups by FlightInfo.DepartureDelay and than show 10 with the highest average delay, but beside grouping I'm completely stuck on how to proceed further. 我知道我应该通过FlightInfo.Origin对FlightInfo进行分组,然后通过FlightInfo.DepartureDelay对这些组进行平均,而不是显示具有最高平均延迟的10,但除了分组之外,我完全坚持如何继续进行。

Thank you in advance for any help! 预先感谢您的任何帮助!


Here is the example of one of previous questions that I was able to answer: 以下是我能够回答的先前问题之一的示例:

Q: The weighted arrival delay of a flight is its arrival delay divided the distance. 问:航班的加权到达延误是其到达延迟除以距离。 What was the flight with the largest weighted arrival delay out of Boston, MA? 马萨诸塞州波士顿加权到达时间最长的航班是什么?

A: A:

var weighted = (from FlightInfo in Flights
               where FlightInfo.Origin == "Boston MA"
               orderby (FlightInfo.ArrivalDelay / FlightInfo.Distance) descending
               select FlightInfo).Take(1);

You could do this. 你可以做到这一点。

var top10 = Flights.GroupBy(g=>g.Origin) // groupby origin 
                  .OrderByDescending(x=> x.Sum(f=> f.ArrivalDelay / f.Distance))  // Get the weighted delay for each fight and use for ordering.
                  .Select(x=>x.Key)  //Airport or Origin (Modify with what you want)
                  .Take(10)
                  .ToList() ;
var result = flights
    .GroupBy(f => f.Origin)
    .OrderByDescending(g => g.Average(f => f.DepartureDelay))        
    .Take(10)
    .Select(g => new
    {
        AirportName = g.Key,
        Flights = g.ToList()
    });

The last .Select parameter depends on what you want. 最后一个.Select参数取决于你想要的。

var topTen = flights.
            GroupBy(g => g.Origin).
            Select(g => new { Origin = g.Key, AvgDelay = g.ToList().Average(d => d.DepartureDelay) }).
            OrderByDescending(o => o.AvgDelay).
            Take(10);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM