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

Vb.net 计算用逗号分隔的每个值的总和,vb.net,Vb.net,如何使用此正确代码按逗号性别计算值之和: Textbox1.Text= 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 代码: 解释和评论 Private Sub OPCode() 'It seems all the numbers you are using are Integers 'so just use Integer as the type Dim

如何使用此正确代码按逗号性别计算值之和:

Textbox1.Text=

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

代码:


解释和评论

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。 选择manyFunctionx x.Split,c。 其中functionx Single.TryParsex,无。 SUMFonfiction x Single.Parsex.ToStringf1 如果必须为每个..循环使用,则可以使用以下方法:

总尺寸=0F 对于TextBox1.行中的每一行 总计+=数组.FindAllline.Split,c, Functionx Single.TryParsex,无任何内容。 SumFunctionx Single.Parsex 下一个 TextBox2.Text=total.ToStringf1 我非常喜欢一句台词。 试试这个:

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

首先,不要拆分文本。文本框具有Lines属性。这是一个例子,说明了为什么我总是喋喋不休地阅读文档。这样做的一个好处是,你可以收集到你可能根本没有寻找过的信息。阅读TextBox类文档的人可能会看到Lines属性,即使他们没有看到;第二,很明显,你的数据包含多个用逗号分隔的数字,但我在代码中看不到任何东西可以处理这个问题。你似乎还没试过那个角色。正如您应该经常做的那样,您应该做的第一件事不是编写代码。将其视为手动练习,并制定获得所需结果所需的步骤。一旦你有了每次都有效的详细步骤,那就是你需要在代码中实现的算法。如果您在编写代码之前不知道代码必须做什么,那么您真的没有尽全力。看看@jazakari上的Split函数,他们已经知道Split函数,因为他们正在使用它,虽然不正确地拆分文本(这不是必需的),但没有使用它拆分单独的行,这是必需的。请打开选项Strict。这是一个由两部分组成的过程。首先,对于当前项目-在解决方案资源管理器中双击“我的项目”。选择左边的Compile。在“选项严格”下拉列表中,选择“启用”。第二,对于未来的项目-进入工具菜单->选项->项目和解决方案->VB默认值。在“选项严格”下拉列表中,选择“启用”。这将使您在运行时免受bug的困扰。它工作得非常好并且正确,这正是您所需要的。
TextBox1.Text = String.Join(",", TextBox1.Lines).Split(","c).Select(Function(s) CInt(s.Trim())).Sum().ToString()