2017-08-17 111 views
1
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; 
+0

至少你可以不使用计...(MaleCount和FemaleCount)... – Spawn

回答

0

免责声明:我在Groovy编程,但是这不应该在这种情况下的差异。

如果你不想这样,也许使用链式.GroupBy().Where()...解决方案:

拆分studentsmaleStudentsfemaleStudents(使用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; 
+0

我觉得比上次'.ToList()'没有必要。 –

+0

我认为,在前两个'Where'之后,首选写'.ToList()'。 –

+0

最重要的是,如果MaleStudents为空,那么'Max()'将失败。 –

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建议,栽培大豆可能会叫的次数太多,事实上,它会被调用一次组内每一个学生,这是不必要的,只有我们需要为每个组计算一次最大值。 如果这是一个问题,你可以这样做:

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

很好的回答,但对我来说,这是很难称之为它“更简单”^ _^ – Spawn

+0

恐怕g.Max(i => i.Marks)将会被调用太多次 –

+0

@AlexeySubbota,是的,你是对的。我相应地编辑了我的答案。 – areller