用循环或其他方式简化C#行

时间:2013-11-21 21:09:47

标签: c# loops

抱歉愚蠢的问题,无论如何要用循环来简化这一行,所以我可以执行N次,同时每次增加credit1和grade1?

    totalpoints = totalpointcalc(totalpoints, credit1.Text, grade1.Text);
            totalpoints = totalpointcalc(totalpoints, credit2.Text, grade2.Text);
            totalpoints = totalpointcalc(totalpoints, credit3.Text, grade3.Text);

如果你能提供一些见解,谢谢你们。)

2 个答案:

答案 0 :(得分:4)

一般来说,只要您拥有名为var1var2,... varN的变量,就应该使用数组(或列表)。

创建一个数组来存储creditgrade控件,然后遍历这些数组:

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);
}

答案 1 :(得分:1)

您可以使用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));