在 C# Groupby Select 中使用 ForEach 或其他函数将一列聚合到结果数组中

In C# Groupby Select using a ForEach or other function to aggregate one column into a array of results

我有一个 groupby 函数,它在 select 中创建一系列列。对于其中一个列,我想要 return 保存在该列 header 下的字段的结果数组,但我似乎无法弄清楚如何在 linq 中编写此查询。

示例代码

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"]



});

如果不知道你的对象是什么样子就很难确定,但大概你可以使用 Select?

StudentNames = a.Select(r => r.StudentName).ToArray()