I have a code in which it pings a server and then returns the elapsed time into a textbox and each is separated with a line break. I want to determine the maximum, minimum and average time elapsed from the returned values in the textbox. I know in order to determine the average I have to add all the values and divide them by the amount of times I pinged the server, which the user inputs in another textbox which can be easily stored as a variable, but I don't know how to add the values in a single textbox. I also have no idea how to determine the maximum and minimum values (maybe using a < or > equation?).
1 Answer
If you are certain that every line in the text box is a number, you can do this:
Dim numbers = txtBox.Text.Split(vbCrLf).Select(Function(line) Double.Parse(line)).ToList()
Dim maximum = numbers.Max()
Dim minimum = numbers.Min()
Dim average = numbers.Average()
If you are not certain that every line is a number, then the statement that initializes numbers may throw an exception as it attempts to parse a non-number as a Double.
In that case, you could say
Dim lines = txtBox.Text.Split(vbCrLf)
Dim numbers = new List(of Double)
Dim unparseableLines = new List(of String)
For Each line in lines
Try
numbers.Add(Double.Parse(line))
Catch ex as FormatException
unparseableLines.Add(line)
End Try
Next
' maybe report the contents of unparseable to the user?
The code as written uses the existing functionality in LINQ for finding Max, Min, and Average. If you want to implement Max or Min in a language that doesn't have these out of the box, you can do something like
Dim minimum = Integer.MaxValue
For Each number in numbers
If number < minimum Then minimum = number
Next
As @Blackwood mentions, it's better to have a separate, canonical place you keep your data, and just use the text box to show these data to the user. That way you don't have to parse the numbers out of the text box to perform these operations on them; you'll just have the numbers directly from the process that created them.
MaxorMinmethods) any time you want to do a calculation on them.