How to generate a comma-delimited course list for each enrolled student?

I’m currently updating a school management app and facing an issue. I need to display a list of courses for each student, but the courses must appear as a comma-separated string. I’m trying to figure out the most efficient method to achieve this. Below is a basic example of my classes with some modifications:

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Enrollment> Enrollments { get; set; }
}

public class Course
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class Enrollment
{
    public int StudentId { get; set; }
    public int CourseId { get; set; }
}

Could someone advise on how to convert the course list into a comma-separated format for each student efficiently? Thanks for any help provided.

For your school management app, I’d suggest using LINQ combined with string.Join to efficiently generate the comma-separated course list for each student. Here’s a concise approach:

var studentCourses = students.Select(s => new
{
    StudentName = s.Name,
    Courses = string.Join(", ", s.Enrollments
        .Join(courses, e => e.CourseId, c => c.Id, (e, c) => c.Name))
});

This query joins the Enrollments and Courses based on CourseId, selects the course names, and then uses string.Join to create the comma-separated list. The result is a collection of anonymous objects containing each student’s name and their course list as a string.

You can then easily iterate over this collection to display or further process the data as needed. This method is both concise and performant, especially for larger datasets. Remember to handle potential null references and empty lists in a production environment.

Hey Oliver63! :wave: That’s an interesting challenge you’ve got there. Have you considered using LINQ with string.Join? It could make your life a lot easier! :wink:

I’m curious though - how many students and courses are we talking about here? Depending on the scale, you might want to think about performance optimization.

Here’s a quick idea off the top of my head:

var courseList = students.Select(s => new
{
    StudentName = s.Name,
    Courses = string.Join(", ", s.Enrollments
        .Join(courses, e => e.CourseId, c => c.Id, (e, c) => c.Name))
});

This should give you a nice, clean list of students with their comma-separated courses. What do you think? Would this work for your app?

Also, I’m wondering - are you planning to allow students to filter or search through their courses later? That might influence how you want to store this data. Have you thought about that aspect?