用循环或其他方式简化C#行
本文关键字:方式简 其他 循环 | 更新日期: 2024-04-03 09:59:46
很抱歉出现愚蠢的问题,有没有办法用循环来简化这一行,这样我就可以执行N次,同时每次增加credit1和grade1?
totalpoints = totalpointcalc(totalpoints, credit1.Text, grade1.Text);
totalpoints = totalpointcalc(totalpoints, credit2.Text, grade2.Text);
totalpoints = totalpointcalc(totalpoints, credit3.Text, grade3.Text);
如果你能提供一些见解,谢谢:)
一般来说,任何时候都有名为var1
、var2
。。。varN
,您可能应该使用数组(或列表)。
创建一个数组来存储credit
和grade
控件,然后循环使用这些数组:
var credit = new[] { credit1, credit2, credit3 };
var grade = new[] { grade1, grade2, grade3 };
...
for(var i = 0; i < credit.Length; i++)
{
totalpoints = totalpointcalc(totalpoints, credit[i].Text, grade[i].Text);
}
您可以使用匿名类型的Enumerable.Aggregate
方法:
var creditGrades = new[]
{
new { credit = credit1.Text, grade = grade1.Text },
new { credit = credit2.Text, grade = grade2.Text },
new { credit = credit3.Text, grade = grade3.Text }
};
var total = creditGrades.Aggregate(0, (i, x) =>
totalpointcalc(i, x.credit, x.grade));