使用C#中的foreach循环将项添加到数组中

时间:2015-10-27 19:48:44

标签: c# arrays loops foreach

我正在尝试做一个需要使用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];
        }

很抱歉,如果有人问过,但我找不到帮助我的答案。

3 个答案:

答案 0 :(得分:2)

您可以使用foreach循环遍历names数组,并阅读如下所示的分数

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

答案 1 :(得分:2)

你应该有一个类:

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

答案 2 :(得分:0)

也许你的意思是这样的:

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++];
}