Search code examples
linqsum

LINQ Syntax for query using Sum()


I want to calculate a Sum value using fields from 2 tables and can't work out the syntax.

var x = (from l in context.Lessons
join t in context.Tariffs on l.TariffId equals t.Id
where l.StudentSemesterId == studentSemesterId
select new {
                lessonCost = (t.Rate) * (l.Duration / 60)
            });

This returns a set of values for individual lessons. How do I get the Sum total of these lessons?


Solution

  • You are selecting a new IEnumerable of an anonymous object type. Just select the correct value you are looking for. Then you have IEnumerable of float/double/decimal/whatever. Then take the resulting sum of that query.

       var x = (from l in context.Lessons
                join t in context.Tariffs on l.TariffId equals t.Id
                where l.StudentSemesterId == studentSemesterId
                select (t.Rate) * (l.Duration /60)).Sum();