[英]How To Add Items In A Multi-Dimensional Jagged Array?
I am trying to add items to an already existing jagged array and I am having some trouble. 我试图将项目添加到一个已经存在的锯齿状数组中,但遇到了一些麻烦。 My program is a console application that is used to deal with student grades (adding students, deleting students, changing names, adding grades to various students, etc).
我的程序是一个控制台应用程序,用于处理学生成绩(添加学生,删除学生,更改姓名,为各个学生添加成绩等)。 I am reading in a sequential file that contains student ID, name, and then the grades (0-100) for each student.
我正在读取一个包含学生ID,姓名和每个学生的成绩(0-100)的顺序文件。 I decided to use a jagged array because I don't know how many grades each student will have, nor do I know how many students I will have.
我决定使用锯齿状的数组,因为我不知道每个学生将要获得多少年级,也不知道我将要拥有多少个学生。
Right now I am trying to add grades to existing students. 现在,我正在尝试为现有的学生增加成绩。 My text file looks like this:
我的文本文件如下所示:
00000,Mimzi Dagger,100,50,75,70,45,10,98,83
00001,Alexander Druaga,89,45,80,90,15,73,99,100,61
00002,Nicholas Zarcoffsky,100,50,80,50,75,100,100
00003,Kantmiss Evershot,50,100
I want to be able to use a For loop and search for the student ID that the user enters, once I find that student ID I want to add a grade under that student. 我希望能够使用For循环并搜索用户输入的学生ID,一旦找到该学生ID,便想在该学生下添加成绩。 Here is a piece of my code, but it doesn't work.
这是我的一部分代码,但是没有用。
for (int i = 0; i < studentArray.Length; i++)
{
if (studentID == studentArray[i][0])
{
studentArray[i][studentArray[i].Length + 1] = newGrade;
}
}
While this is something that I would never, ever do in the real world... I think it does satisfy your constraints for the assignment. 尽管这是我在现实世界中永远都不会做的事情……我认为它确实满足了您对作业的限制。
class Program
{
static void Main(string[] args)
{
List<List<string>> dataList = new List<List<string>>();
dataList.Add(new List<string> { "00000", "Mimzi Dagger", "100", "50", "75", "70", "45", "10", "98", "83" });
dataList.Add(new List<string> { "00001", "Alexander Druaga", "89", "45", "80", "90", "15", "73", "99", "100", "61" });
dataList.Add(new List<string> { "00002", "Nicholas Zarcoffsky", "100", "50", "80", "50", "75", "100", "100" });
dataList.Add(new List<string> { "00003", "Kantmiss Evershot", "50", "100" });
for (int i = 0; i < dataList.Count; i++)
{
foreach (var item in dataList[i])
{
Console.WriteLine(item);
}
}
Console.ReadLine();
}
}
This would be the most basic way of doing what you want: 这将是您要做的最基本的方法:
for (int i = 0; i < studentArray.Length; i++)
{
if (studentID == studentArray[i][0])
{
Array.Resize(ref studentArray[i], studentArray[i].Length + 1);
studentArray[i][studentArray[i].Length - 1] = newGrade;
}
}
Personally I find that a bit of a brain pain. 我个人觉得有点脑痛。
I'd rather write it like this: 我宁愿这样写:
for (int i = 0; i < studentArray.Length; i++)
{
if (studentID == studentArray[i][0])
{
studentArray[i] =
studentArray[i]
.Concat(new [] { newGrade })
.ToArray();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.