ASP.Net获取带有值的列,添加它们然后除

时间:2011-02-14 10:59:20

标签: asp.net average

我已经有了一些正常工作的代码,但它似乎有点像这样做的方式,并想知道是否有人有任何关于如何整理它的想法

这是我的代码

Dim TotalNumber As Double

    Dim NumberFilled As String

    NumberFilled = Nothing

    For x = 0 To drCode2a.Tables(0).Columns.Count - 1

        If Not drCode2a.Tables(0).Rows(0)(x).ToString() = "0" Then

            NumberFilled += drCode2a.Tables(0).Rows(0)(x).ToString() & "-"

            TotalNumber = TotalNumber + drCode2a.Tables(0).Rows(0)(x).ToString()

        End If
    Next

    Dim delimiters As Char() = New Char() {"-"c}

    Dim TotalNumberFilled As String() = NumberFilled.Split(delimiters, StringSplitOptions.RemoveEmptyEntries)

    Dim AverageRating As Double = TotalNumber / TotalNumberFilled.Length

Response.Write(NumberFilled & "<br/>" & TotalNumber & "<br/>" & AverageRating)

基本上我的示例NumberFilled = "1-2-"TotalNumber = 3以及AverageRating = 1.5

它显示填充了2列,它们相等的总数为3,因此平均值= 1.5

正如我所说,它的工作方式应该如此,但如果可能的话,我想整理一下

谢谢

2 个答案:

答案 0 :(得分:2)

Dim totalNumber as Double = 0
Dim count as Integer = 0

For x = 0 To drCode2a.Tables(0).Columns.Count - 1
  Dim current as Double = 0
  If Double.TryParse(drCode2a.Tables(0).Rows(0)(x).ToString(), current) AndAlso current <> 0 Then
    count += 1
    totalNumber += current
  End If
Next

Dim averageRating as Double = totalNumber / count

答案 1 :(得分:1)

这是另一种选择。我不知道它一定更好,但它确实使用了比字符串快一点的StringBuilder对象,并且它将总值保持为双倍而不是执行double to string to double conversion。

Dim NumberFilled As New StringBuilder("")
Dim TotalNumber as Double
Dim ColumnsFilled as Integer = 0

For each column as DataColumn in drCode2a.Tables(0).Columns
    Dim value = drCode2a.Tables(0).Rows(0)(column.ColumnName).ToString()
    If Not "0".Equals(value, StringComparison.OrdinalIgnoreCase) Then

        If NumberFilled.Length > 0 Then NumberFilled.Append("-")
        NumberFilled.Append(value)
        TotalNumber = Convert.ToDouble(value)
        ColumnsFilled += 1

    End If
Next