Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 林克群比。返回数据子集的前一项_C#_Sql_Linq_Group By - Fatal编程技术网

C# 林克群比。返回数据子集的前一项

C# 林克群比。返回数据子集的前一项,c#,sql,linq,group-by,C#,Sql,Linq,Group By,我有一个航班价格数据表,我想返回到每个目的地的前1名最便宜的航班。该表包含以下基本字段: FlightInfoID AirportFrom AirportTo Price 我尝试了以下方法,但它没有返回我预期的结果,因为特定目的地有多个项目,每个目的地我只需要一个结果,因此如果我有50个目的地,我将返回50个项目 lstBestFlightDealsForAllRoutes.OrderBy(p=> p.Price).GroupBy(x => x.AirportTo).First()

我有一个航班价格数据表,我想返回到每个目的地的前1名最便宜的航班。该表包含以下基本字段:

FlightInfoID
AirportFrom
AirportTo
Price
我尝试了以下方法,但它没有返回我预期的结果,因为特定目的地有多个项目,每个目的地我只需要一个结果,因此如果我有50个目的地,我将返回50个项目

lstBestFlightDealsForAllRoutes.OrderBy(p=> p.Price).GroupBy(x => x.AirportTo).First();
  • 按目的地分组航班
  • 从每组中选择组中最便宜的航班
  • Lniq使2变得困难(最小的功能是无用的),但您可以通过按价格订购每个组并从每个组中选择第一个来做到这一点(性能成本很小),例如

    flights.GroupBy(f => f.Destination).Select(g => g.OrderBy(f => f.Cost)).Select(g => g.First())
    

    切换groupby和orderby。
    from f in lstBestFlightDealsForAllRoutes
    group f by new { f.AirportFrom, f.AirportTo } into g // group by route
    select g.OrderBy(x => x.Price).First() // select cheapest flight