Jawad
Jawad

Reputation: 70

Linq to SQL simple SUM

I was suggested from a friend the following code

var tmp = from allCourses in _db.tblCourseNeededHours orderby allCourses.tblCourse.CourseName where allCourses.Semester == semester select allCourses;

return tmp.Sum(x => x.NeededHoursPerWeek);

but i am receving this error

Cannot implicitly convert type 'double' to 'System.Linq.IQueryable

Any idea how to fix it?

enter image description here

public IQueryable FindSumAllCourseNeededHoursInSemester(string semester)

Upvotes: 1

Views: 432

Answers (2)

DamienG
DamienG

Reputation: 6665

Chris is correct if you want the complete total, if you want it by course name use GroupBy:

var hours = FindAllCourseNeededHoursInSemester(mySemester)
    .GroupBy(g => g.CourseName)
    .Select(c => new { c.Key, c.Sum(a => a.NeededHours) } );

Upvotes: 2

Chris Farmer
Chris Farmer

Reputation: 25396

How about this:

var sum = FindAllCourseNeededHoursInSemester(mySemester).Sum(course => course.NeededHours)

This MSDN article has a good primer on some common LINQ tasks:

http://code.msdn.microsoft.com/windowsdesktop/101-LINQ-Samples-3fb9811b

Upvotes: 5

Related Questions