I’m trying to figure out how to convert the following SQL statement to Entity Framework using Linq:
SELECT SUM(Column1) AS Correct
, SUM(Column2) AS Incorrect
, UserName
FROM Stats
WHERE (StatType = 0)
GROUP BY UserName
ORDER BY UserName
For the purposes of this question, all the column types in the DB are type INT, and there are multiple rows of data per user. I basically want 3 columns in my output, with the total of correct & incorrect selections for each user.
It seems like such a simple SQL statement but whatever I try in something like LinqPad, I always get errors. I must be missing something relatively simple. As soon as I start add a “.Sum” clause I get compilation errors etc.
Stats.Where(s => s.StatType == 0)
.GroupBy(s => s.UserName)
.Select(x => new { Correct = x.Column1
, Incorrect = x.Column2
, User=x.UserName})
.ToList()
The following should do the trick:
Please note that
GroupByreturns anIEnumerable<IGrouping<TKey, TValues>>.That means that the
xinside theSelectis anIGrouping<TKey, TValues>. That in turn is basically just anIEnumerable<T>that contains all rows of that group along with the key of this group.So, to get the sum of all items in a group, you need to use
Sumon the grouping and specify which columns to sum as a parameter to theSummethod.