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. 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. 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();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.