vb.net ArrayList 中值的总和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23651159/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 17:33:08  来源:igfitidea点击:

Total sum of values in an ArrayList

vb.net

提问by friend

 Dim arrLst As New ArrayList
 Dim dblVal as Double

this arrLstconstists of n number of values(Double)

arrLst由 n 个值组成 ( Double)

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

目前我使用以下代码来计算值的总和 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 ?

由于arrList.Sum()在 中不可用VB.NET,是否还有其他方法可以完成相同的工作?

回答by Guffa

Well, first of all, an ArrayListis 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.

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

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 eachand the +=operator it gets even simpler:

使用For each+=操作符变得更加简单:

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

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

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

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

回答by Zohar Peled

Try this:

尝试这个:

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

回答by Nilesh Patel

Try this.

尝试这个。

double doubleSum = doubleList.stream().mapToDouble(Double::doubleValue).sum();