2011-02-14 120 views
1

我有一些代碼正在工作,但它似乎只是一個關於如何操作的方式,想知道是否有人有任何想法如何整理一下ASP.Net獲取具有值的列,然後將它們相加,然後將它們分開

這裏是我的代碼

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 = 3AverageRating = 1.5

這表明,兩列分別填寫,他們等於總爲3故平均值= 1.5

正如我所說的它的工作原理像它應該,但我想整理一下,如果可能的

感謝

回答

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

這裏是一個另類。我不知道它會更好,但它確實使用了比字符串快一些的StringBuilder對象,它將總值保持爲雙精度值,而不是對字符串執行雙精度值的雙精度轉換。

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 
相關問題