You must Sign In to post a response.
  • Category: LINQ

    Linq to Sql Left join and get Average

    Hi ,
    Let's say i have an Linq query :

    var query = from course in _unitOfWork.Course.GetAll()
    join candidate in _unitOfWork.CandidateCourses.GetAll() on course.Id equals candidate.Course_id
    join cr in _unitOfWork.CourseReviews.GetAll() on course.Id equals cr.Course_id into g from rt in g.DefaultIfEmpty()
    where candidate.UserId == CandidateId
    select new CourseFields
    {
    Id = course.Id,
    Course_name = course.Course_name,
    Course_description = course.Course_description,
    Rating = g.Average(x => x.Rating),
    TotalSections = sections.Count(),

    };
    return query;

    Here i am getting exception in calculating Average of Rating, When there is no data in table for that particular course.

    Can someone help where i am doing wrong..
  • #769205
    You can use this code snippet in Linq to Sql Left join and get Average
    from s1 in gzClasses.e_userLongSessions                    
    join s2 in gzClasses.e_userLongSessions
    on new {w = s1.workerId, n = s1.sessionNum}
    equals new {w = s2.workerId, n = s2.sessionNum - 1}
    into joined
    from s2Null in joined.DefaultIfEmpty()
    group new {s1, s2Null} by s1.workerId into g
    orderby g.Key
    select g.Average(e => (e.s2Null.startTime - e.s1.endTime).TotalSeconds);


    Or

    Rating = g.DefaultIfEmpty(0).Average(x => x.Rating),


Sign In to post your comments