Pergunta

 Dim arrLst As New ArrayList
 Dim dblVal as Double

this arrLst constists of n number of values(Double)

at present i use the following piece of code to calculate the sum of values in arrLst

        For i = 0 To arrLst .Count - 1
            If dblVal = 0.0 Then
                dblVal = arrLst .Item(i)
            Else
                dblVal = dblVal + arrLst.Item(i)
            End If
        Next

as arrList.Sum() is not available in VB.NET, is there any other method to do the same job ?

Foi útil?

Solução

Well, first of all, an ArrayList is not a good choice to store values of the same type. You should rather use a List(Of Double), then each value doesn't have to be cast to double when you access it.

Anyhow, you can make your code a lot simpler by just setting the sum to zero before you start:

dblVal = 0.0
For i = 0 To arrLst.Count - 1
  dblVal = dblVal + arrLst.Item(i)
Next

(I know that the variable is zero by default when you declare it, so you could actually skip setting it to zero, but it's good to actually set values that the code relies on.)

Using For each and the += operator it gets even simpler:

dblVal = 0.0
For Each n In arrLst
  dblVal += n
Next

You can also use the method Sum to add all the values, but as you use an ArrayList you have to make it a collection of doubles first:

dblVal = arrLst.Cast(of Double).Sum()

Outras dicas

Try this:

dblVal = 0
arrLst.OfType(Of Double)().ToList(Of Double)().ForEach(Function(dbl) dblVal += dbl)

Try this.

double doubleSum = doubleList.stream().mapToDouble(Double::doubleValue).sum();
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top