Average extension method in Linq for null value

221 views Asked by At

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?

0

There are 0 answers