我有一个数组s()
,如下所示,我想根据值s().Mean
对数组进行排序,值最高或最低,反之亦然。我是VB.NET的新手,所以对任何解决方案都感兴趣。我将所有平均值复制到一个简单的数组中,并尝试执行Array.Sort(s,Compare)
,但收到一条ICompare
错误消息,因此现在对下一步操作有些迷茫。
Public Class Form1
Public Structure Values
Public DateTime As String
Public Value As Double
End Structure
Public Structure QDAS
Public Index As Integer
Public ID As String
Public Description As String
Public PartType As String
Public Operation As String
Public Status As Boolean
Public Mean As Double
Public Nominal As Double
Public USL As Double
Public LSL As Double
Public Deviation As Double
Public ErrorAfterTol As Double
Public Max As Double
Public Min As Double
Public Range As Double
Public TotalTolerance As Double
Public PercentOfTol As Double
Public Repeatability As Double
Public Units As String
Public Values() As Values
End Structure
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim s(5) As QDAS
Dim i
For i = 0 To 5
s(i).Description = "F" & i
ReDim Preserve s(i).Values(5)
For j = 0 To 5
s(i).Values(j).Value = Rnd()
Next
For j = 0 To UBound(s(i).Values)
s(i).Mean = s(i).Mean + s(i).Values(j).Value
Next
s(i).Mean = s(i).Mean / (UBound(s(i).Values) + 1)
Next
MsgBox("Done")
Dim Compare() As Double = Nothing
ReDim Compare(UBound(s))
For i = 0 To UBound(s)
Compare(i) = s(i).Mean
Next
Array.Sort(s, Compare)
End Sub
End Class
答案 0 :(得分:0)
您正在使用的Array.Sort
的重载假定第一个参数是您要排序的键数组,第二个参数是您要排序的值数组。
只需反转参数即可:
' Sort low-to-high
Array.Sort(Compare, s)
或
' Sort high-to-low
For i = 0 To UBound(s)
Compare(i) = -s(i).Mean
Next
Array.Sort(Compare, s)
如果您熟悉Object Initializers,Lambda Expressions和LINQ等更高级的主题,则可以将Button1_Click
处理程序简化为:
Dim CreateQDAS As Func(Of Integer, QDAS) = _
Function (i As Integer) New QDAS With {
.Values = Enumerable.Range(0, 5).Select(Function (j) New Values With { .Value = Rnd() }).ToArray(),
.Mean = .Values.Average(Function (v) v.Value)
}
Dim s = Enumerable.Range(0, 5).Select(CreateQDAS)
' Sort low-to-high
Dim Sorted = s.OrderBy(Function (item) item.Mean)
或
' Sort high-to-low
Dim Sorted = s.OrderByDescending(Function (item) item.Mean)