Reputation: 55
I am pretty new to c# and am coding an assignment that is to output years, courses taken each year, and the students who have taken that class. I am taking this information from an external file that includes all the information. When I try to output the values, I get one class that's taken in 2 different years, but the students are showing up for both years when they have only taken it once.
foreach (Years y in year2)
{
Console.WriteLine("Year: {0}", y.gYear);
foreach (Classes c in class2)
{
if (y.gYear == c.gYear)
{
Console.WriteLine("Class: {0}", c.gCourse);
foreach (Grades g in grade2)
{
if (g.gCourse == c.gCourse )
{
//Console.WriteLine("Student: {0}", g.sID);
foreach (Students s in stud2)
{
if (s.sID == g.sID)
{
Console.WriteLine("{0} {1} | Grade: {2}", s.sFirst, s.sLast, g.gGrade);
}
}
}
}
}
}
Console.WriteLine("");
}
Also, I want to delete duplicate classes. Say for the first year, which is 2015, there are 2 students taking the same course. So in the output, it states the course twice and under each course is both of the students.
Upvotes: 2
Views: 111
Reputation: 107247
You haven't shown your data classes, but with virtual certainty, you've missed out a join condition on Grade to Year (i.e. Grades are the 'fact' field value intersecting between Year, Course and Student).
Without this extra join condition, you are getting the cartesian product of Student Grade 'repeated' for each year that the Course was held, with the only restriction being that the student must have done that course at least once, and that's why you are seeing the same students repeating in every year that the same Course is held.
Your Grades
class should look like so:
class Grades
{
public string gCourse {get; set; }
public int sId {get; set; }
public int gGrade {get; set; }
public int gYear {get; set; } // <<< Use this
}
You can address the unwanted repetition by adding in the extra join condition, like so:
// ... Outer loops
foreach (Grades g in grade2)
{
if (g.gCourse == c.gCourse && g.gYear == y.gYear) // << Additional Join condition
{
foreach (Students s in stud2)
{
if (s.sId == g.sId)
{
Console.WriteLine("{0} {1} | Grade: {2}", s.sFirst, s.sLast, g.gGrade);
}
}
}
}
Upvotes: 1