IEnumerable
两次:
var redefineSchoolDatas = group.Select(g =>
{
var elementsInGroup = g.ToList();
return new RedefineSchoolData
{
ClassName = g.Key,
Count = elementsInGroup.Count,
Students = elementsInGroup.Select(s => new Student
{
StudentName = s.StudentName,
StudentAge = s.StudentAge
}).ToList(),
}
}).ToList();
不过,我建议你不要
Count
RedefineSchoolData
班级。维护
计数
与收藏分开(
Students
)不是个好主意:假设你删除了一个学生-那么你还需要记住更新
计数
class RedefineSchoolData
{
public Student Students { get; set; }
public int Count => Students.Count;
// Other properties kept out for brevity
}
// Now your LINQ statements could be:
var redefineSchoolDatas = group.Select(g =>
new RedefineSchoolData
{
ClassName = g.Key,
Students = g.Select(s => new Student
{
StudentName = s.StudentName,
StudentAge = s.StudentAge
}).ToList(),
}).ToList();