gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:55:48 25 4
gpt4 key购买 nike

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;

最佳答案

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

关于c# - 这个 lambda 表达式可以变得更简单吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45729073/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com