Since_2008
Since_2008

Reputation: 2341

Help convert SQL statement to LINQ Lambda (need help with group by and sum)

Here's the statement to convert to LINQ to SQL (Lambda please)

SELECT [Date], SUM(counted) [Counted], SUM(Time) [Time] FROM dbo.TableName GROUP BY [Date]

This is the raw data without group by and sum

Date                    Counted Time
2011-09-07 00:00:00.000 34      31
2011-09-07 00:00:00.000 6       3
2011-09-07 00:00:00.000 7       3
2011-09-07 00:00:00.000 6       2
2011-09-07 00:00:00.000 7       2
2011-09-07 00:00:00.000 19      4
2011-09-07 00:00:00.000 13      4
2011-09-07 00:00:00.000 11      4
2011-09-07 00:00:00.000 14      3
2011-09-07 00:00:00.000 0.75    3

These are the results after group by and sum are applied

Date                    Counted Time
2011-09-07 00:00:00.000 117.75  59

This is what I have so far, but I'm very confused when it comes to doing the group by and sum. Obviously my syntax is way off lol.

var q = context.TableName.Where(...)
               .GroupBy(x => new { x.Date})
               .Sum(x => x.Counted, x.Time????)
               .Select(x => x.Date, x.Counted, x.Time;

Upvotes: 1

Views: 1154

Answers (2)

Mitja Bonca
Mitja Bonca

Reputation: 4546

What about usng Sum() extension method:

var query = table.AsEnumerable().Select(s => s.Field<int>("counted")).Sum();

Upvotes: 0

Tim Rogers
Tim Rogers

Reputation: 21713

var q = context.TableName
           .GroupBy(x => x.Date)
           .Select(g => new { 
               Date = g.Key,
               Counted = g.Sum(x => x.Counted), 
               Time = g.Sum(x => x.Time)
           });

Upvotes: 6

Related Questions