I have an application that creates courses for a university and adds students to the created courses. I pass the course info from my frontend using a dto for data security. The code in my service, using a foreach works, but the one with the linq does not. The code for my entities, which are students and courses, and my service is below:
public class Student
{
public string studentName {get; set;}
public int idCourse {get; set;}
}
public class Course
{
public Course()
{
Students = new List<Student>();
}
public int id {get; set;}
public string courseName {get; set;}
public ICollection<Student> Students {get; set;}
}
public class CourseDTO
{
public string courseNameDTO {get; set;}
public List<string> StudentsFromDTO {get; set;}
}
public class Service(CourseDTO dto)
{
Course createdCourse = new Course
{
courseName = dto.courseNameDTO;
}
foreach(var studentToAdd in dto.StudentsFromDTO)
{
var student = new Student
{
idCourse = createdCourse.id;
studentName = studentToAdd;
}
createdCourse.Students.Add(student);
}
// add the created course in the database
}
Basically, a course has many students, which are added after the new course is created. In my service I loop through the students names and add each of the individually which is not the most efficient, so I tried to write a linq, but it doesn't work:
createdCourse = createdCourse.AddRange(dto.StudentsFromDTO.Select(s => new Student { idCourse = createdCourse.id;
studentName = s; }));
Any way to refactor the code to be fewer lines or a better linq? Cheers!