这是一种可能的解决方案[未经测试]。该AddNearestColumn()
方法遍历每一行并获取到表中其他点的距离列表。然后它遍历列表并获取最小值。您应该使用distances.Sort()
inAddNearestColumn()
而不是手动循环,但我会把它留给您。:-)
Public Sub ProcessTable(table As Data.DataTable)
AddNearestColumn(table)
End Sub
Private Sub AddNearestColumn(table As Data.DataTable)
table.Columns.Add("Nearest", GetType(Double))
For Each r As Data.DataRow In table.Rows
Dim distances As List(Of Double) = GetDistancesFromPoint(table, r)
Dim nearest As Double = Double.MaxValue
For Each distance As Double In distances
If (distance < nearest) Then nearest = distance
Next
r.Item("Nearest") = nearest
Next
End Sub
Private Function GetDistancesFromPoint(table As Data.DataTable, referenceRow As Data.DataRow) As List(Of Double)
Dim output As New List(Of Double)
For Each r As Data.DataRow In table.Rows
Dim referenceId As String = CStr(referenceRow.Item("ID"))
Dim rowId As String = CStr(r.Item("ID"))
If (rowId = referenceId) Then Continue For
Dim x1 As Double = Convert.ToDouble(referenceRow.Item("X"))
Dim y1 As Double = Convert.ToDouble(referenceRow.Item("Y"))
Dim x2 As Double = Convert.ToDouble(r.Item("X"))
Dim y2 As Double = Convert.ToDouble(r.Item("Y"))
output.Add(Math.Sqrt(((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1))))
Next
Return output
End Function