在C#中使用foreach循环将项添加到数组中
本文关键字:添加 数组 foreach 循环 | 更新日期: 2023-09-27 18:19:34
我正在尝试做一项家庭作业,该作业需要使用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];
}
如果有人问我这个问题,我很抱歉,但我找不到对我有帮助的答案。
您应该有一个类,如:
class Student
{
public string Name {get; set; }
public int Score {get; set; }
}
和类似CCD_ 1的
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;
}
您可以使用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();
也许你的意思是:
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++];
}
使用span,您可以使用如下提供的枚举器获得引用变量:foreach (ref var el in span) {...}
。因为它们是refs,所以您可以修改数组中的值。
不推荐使用,因为foreach循环在几乎任何语言中都没有修改的意图。某些语言(包括C#)中的枚举器和迭代器不允许像使用Add
或Remove
方法那样修改集合。