How to do aggregation without "group by" in Linq?
6 answers
morning Alan:
int count = (from a in myContext.MyStuff
select a).Count();
Assuming myContext is DataContext.
Note that this gives you immediate execution that you may not need.
Instead, you can store the query results in var:
var allResults = from a in myContext.MyStuff
select a;
//sometime later when needed
int count = allResults.Count(); // executes the SQL query now!
+4
source to share
There are many non-grouping grouping operators in LINQ. Alan's answer shows you the operator Count
, but MSDN lists others .
EDIT: Seeing your edit, it looks like you want Average .
+2
source to share
It should be noted that Alan LINQ code will give exactly AlanR SQL code, despite what you might assume otherwise.
However, caution should be exercised. If it was written as:
var q = from a in MyStuff select a;
int count = q.count();
foreach(MyStuff m in q) {...}
This will then generate two DB queries: the first as "select count (*) ..." and the second as "select * ...."
+1
source to share