I have a problem, imagine the following situation where I receive the following records from the database:
idStudent | className | startTime | EndTime |
---|---|---|---|
1 | English | 9 | 11 |
4 | Spanish | 9 | 11 |
7 | Mathematics | 9 | 11 |
7 | Biology | 9 | 11 |
7 | Sciences | 9 | 11 |
3 | Sciences | 9 | 11 |
Now imagine I have the following class:
public class test
{
public int idStudent { get; set; }
public List<StudentGrade> StudentGrades { get; set; }
}
public class StudentGrade
{
public string className { get; set; }
public int startTime { get; set; }
public int endTime { get; set; }
}
Using Linq, how would I create this same class where I only have a "test" class with a list of StudentGrades?
I tried to do it like this, but I don't know how to create a list:
var allResult = _getAllClass.FindAll();
var resul = allResult.GroupBy(x => x.studentID)
.Select(s => new test
{
idStudent = s.Select(ss => ss.studentID).FirstOrDefault(),
StudentGrades = ///
}
CodePudding user response:
var result = allResult.GroupBy(x => x.studentID, (k, g) => new test
{
idStudent = k,
StudentGrades = g.Select(r => new StudentGrade
{
className = r.className,
startTime = r.startTime,
endTime = r.endTime,
}).ToList()
}).ToList();
CodePudding user response:
You need to process the group to create the List
inside the test
var
allResult = _getAllClass.FindAll();
var result = allResult.GroupBy(x => x.studentID)
.Select(cg => new test {
idStudent = cg.Key,
StudentGrades = cg.Select(c => new StudentGrade {
className = c.className,
startTime = c.startTime,
endTime = c.endTime,
})
.ToList()
})
.ToList();