Andy
Andy

Reputation: 503

Use List<>, Array or something else?

i'm doing some programming exercises from Exercism.io and need some input on how to start on the Grade-School assignment.

The assignment is to add name and grade and receive name from grade index in the form of List<string>.

The first tests for the assignments looks like this:

[Test]
public void New_school_has_an_empty_roster()
{
    Assert.That(school.Roster, Has.Count.EqualTo(0));
}


[Test]
public void Adding_a_student_adds_them_to_the_roster_for_the_given_grade()
{
    school.Add("Aimee", 2);
    var expected = new List<string> { "Aimee" };
    Assert.That(school.Roster[2], Is.EqualTo(expected));
}

I'm not looking for a complete solution but i need some advice on what Roster should be. My thought was that Roster would be a array of List like this:

public List<string>[] Roster = new List<string>[];

The problem with this is that it doesn't pass the first test because i have to assign a length for the array so count will never be 0. I need a push in the right direction on how to solve this.

Upvotes: 0

Views: 195

Answers (3)

Sybren
Sybren

Reputation: 1079

Your list initialisation is wrong, thats why you get error that you have to assign a size for the array. This is how you make a list:

   public List<string> Roster = new List<string>();

But the better way in this case is to create a class Student or use a Dictionary.

Upvotes: 0

AD.Net
AD.Net

Reputation: 13399

If grade is your index then you should use a Dictionary<int, List<string>> structure. The int is the key, in your case grade and the list contains the names of students with that grade.

When you add a grade and student, you check if the dictionary has any value for that grade, if so, then get the value (of type List<string>) and add the student name to that list, otherwise create a new list and add the student name.

Upvotes: 1

Alex Anderson
Alex Anderson

Reputation: 860

I would not use an Array of Lists, that would get confiusing. Read into Object Oriented Programming (OOP) and look at the user of Classes.

I would have a class to represent a Person (or in your case a student) somthing like:

public class Student
{
    public string Name {get; set;}
    public string Grade {get; set; }
}

and store them in a simple List of Students

public List<Student> Roster;

Another way to look at is a Dictionary so,

public Dictionary<string, string> Roster;

where each entry is Student name and Grade so:

Roster.Add("John Mclain", "A*");

You could also look into Enumerations (Enums) to store the grades instead of using Strings.

Upvotes: 2

Related Questions