如何从列表中获取数字的总和

时间:2021-02-23 15:06:13

标签: c# asp.net webforms

生成一组从-100到100的随机数后,如何将所有数相加?

protected void Button1_Click(object sender, EventArgs e)
{
    var textBoxes = new List<TextBox> { TextBox1, TextBox2, TextBox3, TextBox4, TextBox5 };
    var rand = new Random(Guid.NewGuid().GetHashCode());
    foreach (var textBox in textBoxes)
        textBox.Text = rand.Next(-100, 100).ToString();
}

3 个答案:

答案 0 :(得分:1)

               var theSum = textBoxes.Sum(x=>int.Parse(x.Text));

答案 1 :(得分:1)

您可以使用 Linq 生成数字并对值求和。

Random rnd = new Random();
var list = Enumerable.Range(1, 100).Select(x => rnd.Next(-100, 100)).ToList();

int total = list.Sum();

然后填充该列表中的文本框。

for (int i = 0; i < textBoxes.Count; i++)
{
    textBoxes[i].Text = list[i].ToString();
}

答案 2 :(得分:0)

另一个

 int a = 0;
 var res = textBoxes.Sum(x => int.TryParse(x, out a)?int.Parse(x):0);
相关问题