skylake skylake - 1 month ago 13
C# Question

Get average value from EF

I got two tables

Student
and
Course
.

The table
Course
uses
StudentId
as FK key. Inside
Course
table there's
Score
for each course the student have taken.

Now, how do I calculate the total average
Score
related to
StudentId
?

This is how far I got(
Id
= Students id):

var avg = db.Courses.Where(c=> c.StudentId == Id ... ?


Edit: The
Course
table have some
null
in
Score
for unfinished cources.

Answer

Source: Return the Average Value From a Numeric Sequence

Given that a score can be null then you should only take records that have a valid score

var avg = db.Courses
            .Where(c => c.StudentId == Id && c.Score != null)
            .Average(c => c.Score);

If you looking for an average score per student, then you can use both GroupBy and Average.

var avgerages = db.Courses
                  .Where(c => c.Score != null)
                  .GroupBy(g => g.StudentId, c => c.Score )
                  .Select(g => new 
                   {
                       StudentId = g.Key,
                       Average = g.Average()
                   });
Comments