计算用逗号分隔的每个值的总和

  • 本文关键字:计算 分隔 vb.net
  • 更新时间 :
  • 英文 :


我应该如何使用这个正确的代码按逗号性别计算值的总和:

文本框1.文本 =

1,2
7,1
8,1,3
2,71
20
8,1
27,1

·总数: 14 数字总和:153.0

示例二:

1,2
3,4
5,6

·总数: 6 数字总和:21.0

法典:

Dim total As Single = 0.00
For Each line As String In TextBox1.Text.Split(vbLf)
If IsNumeric(line) Then
total += CSng(line)
End If
Next
TextBox2.Text = total

内联解释和注释。

Private Sub OPCode()
'It seems all the numbers you are using are Integers
'so just use Integer as the type
Dim total As Integer
'You can get an array of the lines in the textbox as follows
Dim lines = TextBox1.Lines
'BTW .Split(vbCrLf) won't work .Split expects a Char or Char array
For Each line As String In lines
'If IsNumeric(line) Then
'This will never return true becaus of the comma
'IsNumeric is an old vb6 function replaced by .TryParse methods
'First you need to split your line into however many numbers you have
Dim numbers = line.Split(","c) 'the small c tells the compiler that this String is really a Char
For Each num In numbers
total += CInt(num) 'remember num is still a String so must be changed to a number to do arithmetic
Next
Next
TextBox2.Text = total.ToString
End Sub

如果您的输入 (TextBox1( 包含混合内容,例如:

1, 2
3, 4
5, 6
A, B, C, D
...
Some other text...
a3z
A, 3, D

若要使用 Linq 提取数值并用一行对其进行求和,请执行以下操作:

TextBox2.Text = TextBox1.Lines.
SelectMany(Function(x) x.Split(","c)).
Where(Function(x) Single.TryParse(x, Nothing)).
Sum(Function(x) Single.Parse(x)).ToString("f1")

如果必须使用For Each..Loop,则可以使用 Array.FindAll 方法,如下所示:

Dim total = 0F
For Each line In TextBox1.Lines
total += Array.FindAll(line.Split(","c),
Function(x) Single.TryParse(x, Nothing)).
Sum(Function(x) Single.Parse(x))
Next
TextBox2.Text = total.ToString("f1")

我非常喜欢一个衬里。 试试这个:

TextBox1.Text = String.Join(",", TextBox1.Lines).Split(","c).Select(Function(s) CInt(s.Trim())).Sum().ToString()

最新更新