这个lambda表达式可以变得更简单吗?

Sha*_*hra 1 c# lambda

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)

are*_*ler 6

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)

  • @Spawn如果你没有做过很多"函数式编程",可能会有点难以掌握,但就尺寸而言,它要短得多,它也更容易修改,你可以轻松扩展它以拥有更多的组,您可以轻松地向查询添加更多过滤器,甚至可以使其多线程并行,而不需要任何努力(通过使用AsParallel方法).Linq是一个非常强大的工具,我相信一旦你学会了如何正确使用它,就很难回头. (2认同)