Lambda/LINQ选择最小值

mik*_*gan 5 .net c# linq lambda linq-to-objects

我正在使用.NET GeoCoordinate类编写一个函数.我们有一个Airport类和一个City类,它们都定义了自己的类GeoCoordinate.

我需要选择最近的机场相对于城市,我正在尝试使用该GetDistanceTo()方法.

我现在拥有的内容如下:

Airport a = Airports.GetAllActiveAirports().Min(this.Coordinates.GetDistanceTo(n.Profile.Coordinates));
Run Code Online (Sandbox Code Playgroud)

另一个(工作)功能,按距离检索最近的机场列表:

List<Airports> airports = Airports.GetAllActiveAirports();
var nearby = 
    from a in airports
    where this.Coordinates.GetDistanceTo(a.Profile.Coordinates) > d
    select a;
foreach(Airport a in nearby)
{ 
    airports.Remove(a); 
}
Run Code Online (Sandbox Code Playgroud)

我已经看过使用LINQ和lambdas在一行中做这样的事情的例子,但我不完全确定如何执行这个...任何指针?

i3a*_*non 6

如果我收到您的问题,此行将获得从坐标到活动机场的最小距离.

Airports.GetAllActiveAirports().Min(_ => Coordinates.GetDistanceTo(_.Profile.Coordinates))
Run Code Online (Sandbox Code Playgroud)

如果您想要有问题的机场,那么:

var airports = Airports.GetAllActiveAirports();
var closest = airports.First(_ => Coordinates.GetDistanceTo(_.Profile.Coordinates) == airports.Min(_ => Coordinates.GetDistanceTo(_.Profile.Coordinates)))
Run Code Online (Sandbox Code Playgroud)

您不必将它保持在一行...... Visual Studio不会耗尽空间.

一个更好的选择,没有在每次迭代中得到最小值将是:

var airports = Airports.GetAllActiveAirports();
var minDistance = airports.Min(_ => Coordinates.GetDistanceTo(_.Profile.Coordinates))
var closest = airports.First(_ => Coordinates.GetDistanceTo(_.Profile.Coordinates) == minDistance)
Run Code Online (Sandbox Code Playgroud)

  • @mike你绝对应该使用最后一个选项:在`nearest`查询之前计算`minDistance`.这种方式最多可以实现`2*n``GetDistanceTo()`调用,当`First`里面的`Min`可以接受`n*(n + 1)`调用时! (2认同)

Ere*_*mez 5

接受的答案会导致GetDistance每个机场2 次呼叫。以下是一次完成的方法:

var closestAirport = Airports.GetAllActiveAirports()
    .Select(x => new {
        Airport = x, 
        Distance = this.Coordinates.GetDistanceTo(x.Profile.Coordinates)})
    .Aggregate((a1, a2) => a1.Distance < a2.Distance ? a1 : a2)
    .Airport;
Run Code Online (Sandbox Code Playgroud)