在计算平均值时处理空值?

时间:2016-05-09 23:03:27

标签: vb.net null

我正在尝试计算出价的平均值,但有时候它会有空值。我的代码是:

 Private Sub count()
    Dim sum As Decimal
    Dim dgvr As System.Windows.Forms.DataGridViewRow
    For Each dgvr In Me.CustAgentListDataGridView.Rows
        sum += dgvr.Cells("Price").Value
    Next dgvr
    Dim n As Integer
    n = Me.CustAgentListDataGridView.Rows.Count
    Dim avg As Decimal
    If (n > 0) Then
        avg = sum / n
    Else
        avg = 0
    End If
    txtavgbidprice.Text = avg.ToString("$ 0.00")
End Sub

1 个答案:

答案 0 :(得分:1)

请参阅下面清理过的代码......我评论了整个过程,以便您可以看到差异......

代码尝试和测试

 Private Sub count()
    Dim sum As Decimal
    Dim nDec As Decimal
    For Each dgvr As DataGridViewRow In Me.CustAgentListDataGridView.Rows
       If Not dgvr.IsNewRow AndAlso Decimal.TryParse(dgvr.Cells("Price").Value.ToString,nDec) Then 'make sure it's not a new row and we can parse out the value into the correct type...
          sum += CDec(dgvr.Cells("Price").Value)
       End If            
    Next

    'if we have a sum, then we should have some rows...
    Dim avg As Decimal
    If sum > 0 Then
        avg = sum / CustAgentListDataGridView.Rows.Count
        txtavgbidprice.Text = avg.ToString("$ 0.00")
    End If

End Sub

这是一种Linq方法,我们将每行投出,确保它不为空,并且它不是新行,最后得到平均值...

txtavgbidprice.Text = CDec(DataGridView1.Rows.Cast(Of DataGridViewRow)().Where(Function(x) x.Cells("Price").Value IsNot DBNull.Value AndAlso Not x.IsNewRow).Average(Function(r) CDec(r.Cells("Price").Value))).ToString("$ 0.00")