-1

I want to perform some calculations on my list List<StudentGrades> studentList such as the average, mean, mode, etc.

The studentGrades class has the following properties:

  • studentName,
  • midtermGrade,
  • finalExamGrade.

How do I extract a certain property from the list and perform arithmetic operations on it?

The following code expands on the StudentGrades class.
I'm thinking of using some sort of traversal technique to add the elements together, something like studentList.find(i).getMidtermScore , which leads to my next question.

public class StudentGrades
{
    public string studentName;
    public int midtermGrade;
    public int finalExamGrade;

    public StudentGrades()
    {
       //initialize variables to 0 or ""
    }
   
    //some methods here
    //example
    private void getMidtermScore()
    {
        return this.midtermGrade;
    }

   public string toString()
   {
       string result = "student: " + studentName + " midterm grade: " + midterm + ...etc;
       return result;
   }
}

Also, how does someone grab an element at a specific index from a list?
In Java, for ArrayLists or Lists, we use the get(//some value) method to do so.
Looking at the Microsoft docs documentation for C# list, the counterpart is the find() method? Not really sure.

LopDev
  • 823
  • 10
  • 26
  • `var max = studentList.Select(z => z.finalExamGrade).Max();` or `var max = studentList.Max(z => finalExamGrade);` may get you started. – mjwills Sep 14 '20 at 06:50
  • `Also, how does someone grab an element at a specific index from a list?` I'd start with `var first = studentList[0];` – mjwills Sep 14 '20 at 06:51
  • LINQ has clearly-documented, easy-to-use features to do exactly what you want. For any scenario where the built-in `Average()`, `Min()`, and `Max()` methods don't suffice, there's `Aggregate()`. See duplicates. – Peter Duniho Sep 14 '20 at 07:19

1 Answers1

1
myList.Select(x => x.midtermGrade).Average() //average of midterm grades 
myList.Select(x => x.midtermGrade).Min() //lowest midterm grade
myList.Select(x => x.midtermGrade).Max() //highest midterm grade

myList[0] gives you first element of the list.

myList[0].midtermGrade gives you midterm grade of the first element of the list

Derviş Kayımbaşıoğlu
  • 28,492
  • 4
  • 50
  • 72