开发者

ASP.Net get columns with values, add them and then divide

开发者 https://www.devze.com 2023-02-10 14:16 出处:网络
I\'ve got some code which is working as it should but it just seems like a bit of a round about way in doing it and wondered if anyone had any ideas of how to tidy it up

I've got some code which is working as it should but it just seems like a bit of a round about way in doing it and wondered if anyone had any ideas of how to tidy it up

Here's my code

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)

Basically for my example NumberFilled = "1-2-" and TotalNumber = 3 and AverageRating = 1.5

It shows that 2 columns were filled out and the total they equal is 3 so the average = 1.5

As I said it works like it should but I'd like to tidy up if possible

Thanks


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


Here is an alternative. I don't know that it's necessarily better, but it does make use of the StringBuilder object which is a little faster than strings and it keeps the total values as doubles rather than performing double to string to double conversions.

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
0

精彩评论

暂无评论...
验证码 换一张
取 消