skylake - 1 year ago 73

C# Question

I got two tables

`Student`

`Course`

The table

`Course`

`StudentId`

`Course`

`Score`

Now, how do I calculate the total average

`Score`

`StudentId`

This is how far I got(

`Id`

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

`Course`

`null`

`Score`

Answer Source

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