Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/263.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用循环或其他方法简化C#线_C#_Loops - Fatal编程技术网

用循环或其他方法简化C#线

用循环或其他方法简化C#线,c#,loops,C#,Loops,抱歉这个愚蠢的问题,有没有办法用循环来简化这一行,这样我就可以在每次增加credit1和grade1的同时执行N次 totalpoints = totalpointcalc(totalpoints, credit1.Text, grade1.Text); totalpoints = totalpointcalc(totalpoints, credit2.Text, grade2.Text); totalpoints = totalpoint

抱歉这个愚蠢的问题,有没有办法用循环来简化这一行,这样我就可以在每次增加credit1和grade1的同时执行N次

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

如果您能提供一些见解,谢谢您:)

一般来说,只要您有名为
var1
var2
varN
,您可能应该改用数组(或列表)

创建一个数组来存储
信用
等级
控件,然后在这些数组中循环:

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);
}
var credit=new[]{credit1,credit2,credit3};
变量等级=新[]{1级、2级、3级};
...
对于(变量i=0;i
您可以使用匿名类型的方法:

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

一个问题-将这段(非常可读和可理解的)代码放入循环有什么价值?也就是说,你想在这里解决什么问题?我重复了30次这句话,如果我想改变它的任何方面,那会容易得多。@LucasHolmes-最好是以某种方式将你的学分和分数字段放入相应的列表中。根据您的情况,您可能需要手动执行此操作。我不完全理解这里发生的事情,您能进一步解释一下吗?我很抱歉编码不太流利。@LucasHolmes你对哪一部分感到困惑?第一部分我在创建数组,第二部分我在循环它们?@LucasHolmes-简而言之,他创建了两个数组,然后通过它们的索引([I])循环它们,并在集合中每次更新
totalpoints
。顺便说一句,+1。@LucasHolmes好的,
var
创建一个隐式类型的变量,
new[]{…}
是一个隐式数组初始值设定项。我不得不这样做,因为从代码中不清楚控件的类型。最有可能的情况是,您希望将其替换为
TextBox[]credit=newtextbox[]{…}
(或您正在使用的任何控件类型)。