I have a groupby function that is creating a series of columns in a select. For one one the columns I want to return a array of results of a field saved under that column header, but I can't seem to figure out how to write this queries in linq.
Example code
var res = students.GroupBy(x => x.ClassId).Select(a => new {
ClassHours = a.Sum(r => r.Hours),
AvgAttendance = a.Average(r => r.AttendanceRate),
NumStudents = a.Count(),
// I want to get a list of all student names but not sure how to do this,
I want a array return of student names, I tried with for each but this doesn't seem to work but I'm not sure what to do
StudentNames = a.ForEach(r => return r.StudentName)
// I want to do something like this but make the rest a array e.g. StudentNames = ["Blaise", "Sasha", "Jeff"]
});
CodePudding user response:
Hard to be certain without knowing what your object looks like, but presumably you can you just use Select
?
StudentNames = a.Select(r => r.StudentName).ToArray()