ArrayList 中值的总和 [英] Total sum of values in an ArrayList

查看:32
本文介绍了ArrayList 中值的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 Dim arrLst As New ArrayList
 Dim dblVal as Double

这个 arrLst 由 n 个值组成(Double)

this arrLst constists of n number of values(Double)

目前我使用以下代码来计算总和arrLst

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

因为 arrList.Sum()VB.NET 中不可用,有没有其他方法可以做同样的工作?

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

推荐答案

首先,ArrayList 不是存储相同类型值的好选择.您应该使用 List(Of Double),这样在访问每个值时不必将其强制转换为 double.

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.)

使用 For each+= 运算符,它变得更加简单:

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

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

您也可以使用 Sum 方法来添加所有值,但是当您使用 ArrayList 时,您必须先使其成为双精度集合:

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()

这篇关于ArrayList 中值的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆