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

时间:2017-08-17 07:30:42

标签: 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;

2 个答案:

答案 0 :(得分: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();

编辑:

@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();

答案 1 :(得分:0)

免责声明:我在Groovy中编程,但在这种情况下这不应该有所作为。

如果您不想以这种方式使用链式.GroupBy().Where()...解决方案:

students分为maleStudentsfemaleStudents(使用Where())。

这应该消除了对于男性和女性学生的if-wrappers和Count()的需求。

所以我的选择应该是这样的:

var MaleStudents = students.Where(Std => Std.Gender.ToUpper() == "M");
var FemaleStudents = students.Where(Std => Std.Gender.ToUpper() == "F");

//List for storing top students records           
List<StudentEntity> TopStudents = new List<StudentEntity>();

//Adding records to List
var maxMarksM = MaleStudents.Max(o => o.Marks);
TopStudents = MaleStudents.Where(o => o.Marks == maxMarksM).ToList();

var maxMarksF = FemaleStudents.Max(o => o.Marks);
TopStudents.AddRange(FemaleStudents.Where(o => o.Marks == maxMarksF).ToList());

return TopStudents;