0

Can I somehow calculate the average for different items and choose student(s) with best GPA?

public static List<Student> LoadSampleData()

        {
             List<Student> output = new List<Student>();
            
            output.Add(new Student  { ID = 1, FirstName = "Tim", LastName = "Corey ", Patronymic = "Fitzpatrick ", Group = "A", Math = 5, Programming = 5, Informatics = 5});
            output.Add(new Student  { ID = 2, FirstName = "Joe", LastName = "Smith ", Patronymic = "Mackenzie ", Group = "A", Math = 3, Programming = 3, Informatics = 4});
            output.Add(new Student  { ID = 3, FirstName = "Ellie", LastName = "Williams ", Patronymic = "", Group = "B", Math = 4, Programming = 5, Informatics = 4});
            output.Add(new Student  { ID = 4, FirstName = "Joel", LastName = "Miller ", Patronymic = "", Group = "B", Math = 4, Programming = 4, Informatics = 5});
            

            return output; 

        }

I need it to be calculated approximately according to the following logic (finding the average for all subjects for each student. For example: student_avarage(Math+Programming+Informatics) and find the best score). Without using loops like: for, while, if and etc. ("foreach{}" too)

public static void BestStudentsAvarage()
        {
            List<Student> students = ListManager.LoadSampleData();
            
            var StudentAverage =
            from student in students
            group student by student.ID into studentID
            select new
            {
                
                ID = studentID.Key,
                student_Average = studentID.Average(x => x.(Math+Programming+Informatics))
            };
                var bestGrade = StudentAverage.Max(gr => gr.student_Average);
                var bestIDs_1 = StudentAverage.Where(g => g.student_Average == bestGrade);
                var bestID_1 = bestIDs_1.FirstOrDefault();
                Console.WriteLine($"\nBest student(s) GPA: {bestID_1.ID} \nScore: {bestID_1.student_Average}");
                Console.ReadLine();
        }

1 Answers1

1

I think this is what you actually want(divide the sum of the three subjects through 3):

public static List<(Student student, decimal average)> BestStudentsAvarage(List<Student> students)
{
    return students
        .Select(s => (Student:s,Average:(s.Math+s.Programming+s.Informatics)/3m))
        .GroupBy(g => g.Average)
        .OrderByDescending(g => g.Key)
        .First()
        .ToList();
}

 List<Student> sample = LoadSampleData();
 List<(Student student, decimal average)> bestAvarageStudents = BestStudentsAvarage(sample);
 foreach(var x in bestAvarageStudents)
 {
    Console.WriteLine($"Best student <{x.student.FirstName} {x.student.LastName}> with Average <{x.average}>");
 }

With your example it would output: Best student <Tim Corey> with Average <5>

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939