0

I am facing problem in handling average of empty list.

var groupJoin = studentList.GroupJoin(resultList,  //inner sequence
                                studentKeySelector => studentKeySelector.id, //outerKeySelector 
                                resultKeySelector => resultKeySelector.id,     //innerKeySelector
                                (std, resultsGroup) => new // resultSelector 
                                {
                                    Results = resultsGroup,
                                    StudentName = std.name,
                                    StudentId = std.id
                                }).Select(x => new Output {
                                    name = x.StudentName,
                                    id = x.StudentId,
                                    averageGradePoint = x.Results.Average(y => y.gradePoint)
                                }).ToList();

Here while calculating averageGradePoint, I want to handle the case that I have my list empty. I know there is a method DefaultIfEmpty(0). But averageGradePoint = x.Results.DefaultIfEmpty(0).Average(y => y.gradePoint) gives me System.InvalidOperationException. How to do this?

  • 1
    Clearly it gives you `InvalidOperationException` because `0` isn't the same type as an entry in `Results`. If you rewrote it as `x.Results.Select(y => y.gradePoint).DefaultIfEmpty(0).Average();` it might work. Also, you talk about `null` in your question title. An empty list is not `null`. What problem are you actually trying to solve? – ProgrammingLlama Mar 25 '22 at 07:27
  • Does this question help? https://stackoverflow.com/questions/5467114/average-extension-method-in-linq-for-default-value – sbridewell Mar 25 '22 at 07:32
  • does `x.Results.DefaultIfEmpty(0)` even compile? I would have expected a compiler error complaining about the types. – JonasH Mar 25 '22 at 08:01

0 Answers0