tags:

views:

553

answers:

6

Good morning,

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

Regards, Alan.

+4  A: 

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!
Alan
Sorry, I didn't realize my question wasn't specific enough. I'm going to re-word it a little. thanks anyway.
AlanR
And you owe me a beer for taking the name "Alan" :)
AlanR
Sorry! Had Alan been taken, AlanR would have been my next choice ;)
Alan
+1  A: 

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 * ...."

James Curran
+2  A: 

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.

Jon Skeet
+1  A: 

The answer to modified example (I believe) is:

var average = (from a in MyStuff
              select a.Value).Average();
Alan
I would personally avoid the query expression in that case, and just use: var average = MyStuff.Average(a => a.Value).
Jon Skeet
A: 

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

AlanR
Your query expression probably isn't doing anything useful. Try just s.Average(a => a.Value)
Jon Skeet
What Jon Skeet meant was `series.Average(a => a.Value)`.
Timwi
+1  A: 

A bit sorter

pairs.Average(a=>a.Value)   

If there's no join, group or let, Query Expressions (from ...) are not worth in my opinion.

Olmo