Muqeet Khan
Muqeet Khan

Reputation: 2124

Group by in Linq to sql with an aggregate column

I am having difficulty converting a simple T-SQL statement into a LINQ statement.

select UserName,SUM(Value) FROM UserValues Group By username

I have got so far in C#:

var TcountValues = _context.UserValues.GroupBy(g=>g.UserName);

I am not sure If I am suppose to be using a select after this to get to my Username and aggregate function. At this point I am not even sure if I should be using the group by method in LINQ.

Any help will be appreciated.

Upvotes: 0

Views: 39

Answers (1)

ironstone13
ironstone13

Reputation: 3453

var TcountValues = _context.UserValues
                           .GroupBy(g=>g.UserName)
                           .Select(x=> new 
                           {
                                UserName = x.Key, 
                                Sum = x.Sum(y=>y.Value)
                           });

It would be better to create a class for TcountValues, otherwise you will have a collection of anonymous types, and you won't be able to access the properties of this object in a strongly typed fashion outside of the current scope (method in this case)

Upvotes: 2

Related Questions