Home > Net >  C# - How to find the average from the numbers given by the textbox
C# - How to find the average from the numbers given by the textbox

Time:12-28

I am pretty new on the programming field. I started learning C# and I have a problem. I need to find the average of the given numbers from textboxes.

int wage1 = int.Parse(textBox_wage1.Text);
int wage2 = int.Parse(textBox_wage2.Text);
int wage3 = int.Parse(textBox_wage3.Text);
int wage4 = int.Parse(textBox_wage4.Text);
int wage5 = int.Parse(textBox_wage5.Text);
int wage6 = int.Parse(textBox_wage6.Text);
int wage7 = int.Parse(textBox_wage7.Text);
var average = new int[] { wage1, wage2, wage3, wage4, wage5, wage6, wage7 };
double AverageBruto = Queryable.Average(average.AsQueryable());
lbl_AverageBruto.Text = "Average: "   AverageBruto;`

This works perfectly fine if the user has filled all 7 textboxes, but if they didn't fill at least one of them, it causes an error. can someone help me figure out how I can find the average if they fill only 3 or 4 of the textboxes? Thank you.

CodePudding user response:

You likely don't want to be using an array for this, because if null values are represented by zeros then the average will be off. The wage ints should probably be in an array (The textBox_wages as well but it's not necessary for this example) so you can iterate through them, check for null values, and only add those that aren't null to a list you'll take the average from. Here's one way you could approach it:

int[] wages = new int[8];
int wages[0] = int.Parse(textBox_wage1.Text);
int wages[1] = int.Parse(textBox_wage2.Text);
int wages[2] = int.Parse(textBox_wage3.Text);
int wages[3] = int.Parse(textBox_wage4.Text);
int wages[5] = int.Parse(textBox_wage5.Text);
int wages[6] = int.Parse(textBox_wage6.Text);
int wages[7] = int.Parse(textBox_wage7.Text);
var AverageBruto = new List<int>();
foreach (int x in wages) if (x != null) AverageBruto.Add(i);
AverageBruto = AverageBruto.average();
lbl_AverageBruto.Text = "Average: "   AverageBruto;

You'll have to use System.Linq for this method though.

CodePudding user response:

Let's organize the TextBoxes and then query with a help of Linq:

double AverageBruto = new TextBox[] {
  textBox_wage1, 
  textBox_wage2,
  textBox_wage3,
  textBox_wage4,
  textBox_wage5,
  textBox_wage6,
  textBox_wage7,
}
  .Where(box => !string.IsNullOrWhiteSpace(box.Text))
  .Average(box => int.Parse(box.Text));

lbl_AverageBruto.Text = $"Average: {AverageBruto}";

Here, with a help of Where we choose only TextBoxes which have some Text

  •  Tags:  
  • c#
  • Related