【问题标题】:Adding items to an array using a foreach loop in C#在 C# 中使用 foreach 循环将项目添加到数组
【发布时间】:2015-10-27 19:48:43
【问题描述】:

我正在尝试做一项家庭作业,该作业需要使用 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 与数组或列表或任何类似的东西一起使用。
  • 不确定您要做什么,因为您无法在迭代时更改迭代变量(因此,如果您使用 @mikeTheLair 建议输入分数,则该建议将不起作用)。
  • 也许可以阅读有关foreach 关键字如何工作的书。您也可以在 MSDN 上搜索它以查看一些示例。
  • 你不能用 foreach 循环来做到这一点。这真的是作业吗? foreach 循环用于简单的迭代,您也不能更改迭代数组上的元素。
  • 您可以定义int[] studentScore = new int[5];,然后执行foreach(var i in Enumerable.Range(0,5)) 之类的操作,从技术上讲,您正在使用foreach 循环,但这完全没有意义。也许您打算循环遍历studentName?我假设那个集合已经被填充了?

标签: c# arrays loops foreach


【解决方案1】:

您可以使用 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();

【讨论】:

  • 非常感谢。这非常有效。我曾经尝试过类似这样的东西,但有点搞砸了。
【解决方案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;
}

【讨论】:

  • @juharr 我认为它只是一些代码的一部分,可能会在此代码之后使用。但是对于这段代码,你是对的。
【解决方案3】:

也许你的意思是这样的:

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

【讨论】:

  • 问题说“数组”,所以除非 OP 没有使用正确的术语,否则不会是这样。
  • 不知何故我怀疑 OP 的类还没有涵盖集合类。
  • @crashmstr:将其更改为数组很简单。无论如何使用列表更好(无需跟踪索引)。使用对象列表(而不是两个并行集合)将是最好的解决方案。
  • @mikeTheLiar:我认为这与远程无关。这是一个学习一些东西的机会,问题和答案的存在不仅仅是为了 OP 的利益。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-28
相关资源
最近更新 更多