Reputation: 337
sorry for dumb question, is there anyway to simplify this line with a loop, so i can perform it N times whilst increasing credit1 and grade1 each time?
totalpoints = totalpointcalc(totalpoints, credit1.Text, grade1.Text);
totalpoints = totalpointcalc(totalpoints, credit2.Text, grade2.Text);
totalpoints = totalpointcalc(totalpoints, credit3.Text, grade3.Text);
Thanks if you can shed some insight :)
Upvotes: 2
Views: 105
Reputation: 9847
You could use the Enumerable.Aggregate
method with an anonymous type:
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));
Upvotes: 1
Reputation: 149040
Generally speaking, any time you have variables named var1
, var2
, ... varN
, you should probably be using an array (or list) instead.
Create an array to store your credit
and grade
controls, then loop through those arrays:
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);
}
Upvotes: 4