Sahil Sharma Sahil Sharma - 3 months ago 19
C# Question

Return List using foreach

public string Studentbyteacher(long _id)
{
using (var context = new DbContext())
{
var studentID = (context.TeacherStudent.Where(x => x.TeacherID == _id).Select(x => x.studentID));
foreach (var id in studentID)
{
var strJSON = JsonConvert.SerializeObject(context.Student.Where(x => x.ID == id).ToList());
return strJSON;
}
return null;
}
}


Note: I am getting student ID in array list like [0]1,[1]2,[2]3...so on. So I want to return student details on the basis of ID. Please correct me if I'm wrong.

Answer
public string Studentbyteacher(long teacherId)
{
    using (var context = new DbContext())
    {
        var students = 
            from teacherStudent in context.TeacherStudent.Where(x => x.TeacherID == teacherId)
            let studentId = teacherStudent.studentID
            let student = context.Student.Where(x => x.ID == studentId).Single()
            select student;

        return JsonConvert.SerializeObject(students);
    }
}