var MaleCount = students.Where(Std => Std.Gender.ToUpper() == "M").Count();
var FemaleCount = students.Where(Std => Std.Gender.ToUpper() == "F").Count();
//List for storing top students records
List<StudentEntity> TopStudents = new List<StudentEntity>();
//Adding records to List
if (MaleCount > 0)
{
var maxMarksM = students.Where(o => o.Gender.ToUpper() == "M").Max(o => o.Marks);
TopStudents = students.Where(o => o.Gender.ToUpper() == "M" && o.Marks == maxMarksM).ToList();
}
if (FemaleCount > 0)
{
var maxMarksF = students.Where(o => o.Gender.ToUpper() == "F").Max(o => o.Marks);
TopStudents.AddRange(students.Where(o => o.Gender.ToUpper() == "F" && o.Marks == maxMarksF).ToList());
}
return TopStudents;
Run Code Online (Sandbox Code Playgroud)
var topStudents = allStudents
.GroupBy(s => s.Gender.ToUpper()) // Dividing the students to groups by gender
.Where(g => g.Key == "M" || g.Key == "F") // Including only the Male and Female genders
.Select(g => g.Where(s => s.Marks == g.Max(i => i.Marks))) // From each group, finding the highest mark and selecting from that groups all the student with that mark
.SelectMany(s => s) // selecting all the students from all the inner groups
.ToList();
Run Code Online (Sandbox Code Playgroud)
编辑:
@Alexey Subbota建议g.Max可能会被调用太多次,实际上它会被调用一次给组内的每个学生,这是不必要的,我们只需要为每个组计算一次最大值.如果这是一个问题,你可以这样做:
var topStudents = allStudents
.GroupBy(s => s.Gender.ToUpper()) // Dividing the students to groups by gender
.Where(g => g.Key == "M" || g.Key == "F") // Including only the Male and Female genders
.Select(g => new KeyValuePair<int, IEnumerable<Student>>(g.Max(s => s.Marks), g)) // Storing the group together with it's highest score value
.Select(g => g.Value.Where(s => s.Marks == g.Key)) // From each group, selecting the student that have the highest score
.SelectMany(s => s) // selecting all the students from all the inner groups
.ToList();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
105 次 |
| 最近记录: |