Everything I can find in linq for aggregation has a "group by" clause. How would I write this query in LINQ? I have a list of date-value pairs, and I want to take the average of the values:
SELECT AVG(MySuff.Value) AS AvgValue FROM MyStuff
morning Alan:
int count = (from a in myContext.MyStuff
select a).Count();
Assuming myContext is the DataContext.
Note that is gives you immediate execution, which you may not want.
You could instead store the results of the query in a var:
var allResults = from a in myContext.MyStuff
select a;
//sometime later when needed
int count = allResults.Count(); // executes the SQL query now!
There are plenty of non-grouping aggregation operators in LINQ. Alan's answer shows you the Count operator, but MSDN lists others.
EDIT: Having seen your edit, it looks like you want the Average operator.
The answer to modified example (I believe) is:
var average = (from a in MyStuff
select a.Value).Average();
It should be noted that Alan's LINQ code will yield exactly AlanR's SQL code, despite the fact that you might guess otherwise.
However, care should be exercised here. If it were written as:
var q = from a in MyStuff select a;
int count = q.count();
foreach(MyStuff m in q) {...}
Then that will generate two DB queries : the first as "select count(*)..." and the second as "select * ...."
Thank you all for the help. Here is what I settled on, which works.
(from s in series select s).Average( a => a.Value )
Regards, Alan...R