-3

I am displaying three text box, which get only numbers. User may enter value in one text box or two or three in any order. I want to calculate the average of value entered in those text boxes in C#.

For example. if any one text box contain values, average must be calculate based on 1 (value/1).

if two text box contain values, average must be calculate with 2 (value1+value2)/2

if three text boxes contain values, average must be calculate with 3 (value1+value2+value3)/3.

any one know how to achieve this with less code?

Jamiec
  • 133,658
  • 13
  • 134
  • 193
Lalitha
  • 67
  • 1
  • 11

2 Answers2

2

You could put those values into an array or list and use LINQ's Enumerable.Average. Or calculate it with following query that uses int.TryParse and presumes that the TextBoxes are in the same container control(like a Panel or GroupBox):

int value = 0;
double average = TextBoxPanel.Controls.OfType<TextBox>() // get all TextBoxes from this panel
    .Where(t => int.TryParse(t.Text, out value))  // which Text is parsable to int
    .Select(t => value)                           // select the value that contains the parsed int
    .Average();                                   // use Enumerable.Average to calculate the average
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1

The most trivial approach would be to create a list to contain the values, and leverage the framework to calculate the average of the numbers contained in that list.

In steps, as to not spoon-feed you copy-pasteable code:

  1. Create a numeric list variable
  2. For each textbox:
    1. Check if the textbox contains text
    2. If so, try to parse it as a number
    3. When that succeeds, add the number to the list
  3. Calculate the average of the numbers in the list

Relevant reading material:

Community
  • 1
  • 1
CodeCaster
  • 147,647
  • 23
  • 218
  • 272