0

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
  • 1
    TextBoxes and other Controls are for displaying data to users. They are not the best place to store data. In this case, you had the elapsed times in usable form before you converted them into strings to display in the TextBox. If you store the elapsed times in a List (as well as displaying them in the TextBox, you can process the list (e.g. using the Max or Min methods) any time you want to do a calculation on them. Commented Sep 1, 2015 at 20:18

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.