任何人都可以帮我解决这个问题,我有一个看起来像这样的列表框
Oranges 8,2,7
Apples 0,10,3
Pineapples 6,9,1
我基本上希望能够计算每条线的平均值,并在按下按钮时显示在线的末尾。我有用于计算整个列表框的平均值的代码,但无法弄清楚如何为每一行执行此操作,我正在考虑将正确的代码放入循环中,我有一种感觉我将不得不使用string.parse方法,以便通过','?
分隔数字答案 0 :(得分:0)
正如Blackwood建议您可以(并且应该)将您的水果数据存储在一个单独的类中。在这里,我添加了一个汇总函数,您稍后可以将其用于ListBox ...
Imports System.Text
Public Class Fruit
Public Sub New(ByVal name As String, ByVal numbers As List(Of Integer))
_name = name
_numbers = numbers
End Sub
Private _name As String
Public Property name() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
Private _numbers As List(Of Integer)
Public Property numbers() As List(Of Integer)
Get
Return _numbers
End Get
Set(ByVal value As List(Of Integer))
_numbers = value
End Set
End Property
'Function to calculate the average of the numbers
Public Function getAverage() As Double
If _numbers.Count = 0 Then
Return 0
End If
Dim sum As Integer = 0
For Each num As Integer In _numbers
sum = sum + num
Next
Return sum / _numbers.Count
End Function
'Function to get a summary of the fruit for the ListBox
Public Function getSummary() As String
Dim summary As StringBuilder = New StringBuilder
summary.Append(_name & " ")
For i = 0 To _numbers.Count - 1
If i = (_numbers.Count - 1) Then
summary.Append(_numbers(i) & " ")
Else
summary.Append(_numbers(i) & ",")
End If
Next
summary.Append("Average: " & getAverage())
Return summary.ToString
End Function
End Class
按下按钮时,您会读取文本文件,拆分行并将值放在Fruit对象列表中:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim inputLines As String() = File.ReadAllLines("C:\Temp\data.txt") 'Read all lines of the text file
Dim fruits As List(Of Fruit) = New List(Of Fruit) 'Create a new list of fruits
For Each line As String In inputLines
Dim namesAndNumbers As String() = line.Split(" ") 'Split the line to get an array (of size 2) with the name and numbers
Dim name As String = namesAndNumbers(0)
Dim numbers As String() = namesAndNumbers(1).Split(",") 'Split the second element of the array to get the numbers as array
'Convert the numbers from String to Integer
Dim numberIntList As List(Of Integer) = New List(Of Integer)
For Each number As String In numbers
numberIntList.Add(Integer.Parse(number))
Next
Dim fruit As Fruit = New Fruit(name, numberIntList) 'Create a new Fruit object and add name and numbers
ListBox1.Items.Add(fruit.getSummary) 'Add the summary of the Fruit object to the ListBox
Next
'Do whatever you want with the list of fruits ...
End Sub