[英]Adding items to an array using a foreach loop in C#
我正在尝试做一项作业,要求使用foreach循环将项目添加到数组。 我使用for循环来完成它,但是无法通过foreach循环来解决它。
这就是我需要的,只是在foreach循环中。
for (int i = 0; i < 5; i++)
{
Console.Write("\tPlease enter a score for {0} <0 to 100>: ", studentName[i]);
studentScore[i] = Convert.ToInt32(Console.ReadLine());
counter = i + 1;
accumulator += studentScore[i];
}
抱歉,如果有人提出这个问题,但我找不到可以帮助我的答案。
您可以使用foreach循环遍历名称数组,并读取分数,如下所示
foreach(string name in studentName)
{
Console.Write("\tPlease enter a score for {0} <0 to 100>: ", name);
studentScore[counter] = Convert.ToInt32(Console.ReadLine());
accumulator += studentScore[counter];
counter++;
}
Console.WriteLine(accumulator);
Console.ReadLine();
您应该有一个类似的课程:
class Student
{
public string Name {get; set; }
public int Score {get; set; }
}
和foreach
一样:
var counter = 0;
foreach (student in studentsArray)
{
Console.Write("\tPlease enter a score for {0} <0 to 100>: ", student.Name);
student.Score = Convert.ToInt32(Console.ReadLine());
counter++;
accumulator += student.Score;
}
也许您的意思是这样的:
var studentScores = new List<int>();
foreach (var student in studentName) // note: collections really should be named plural
{
Console.Write("\tPlease enter a score for {0} <0 to 100>: ", student);
studentScores.Add(Convert.ToInt32(Console.ReadLine()));
accumulator += studentScores.Last();
}
如果必须使用数组,则如下所示:
var studentScores = new int[studentName.Length]; // Do not hardcode the lengths
var idx = 0;
foreach (var student in studentName)
{
Console.Write("\tPlease enter a score for {0} <0 to 100>: ", student);
studentScores[idx] = Convert.ToInt32(Console.ReadLine());
accumulator += studentScores[idx++];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.