0

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

6 Answers 6

4

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!
Sign up to request clarification or add additional context in comments.

3 Comments

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

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.

Comments

1

The answer to modified example (I believe) is:

var average = (from a in MyStuff
              select a.Value).Average();

1 Comment

I would personally avoid the query expression in that case, and just use: var average = MyStuff.Average(a => a.Value).
1

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

Comments

1

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.

Comments

0

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

2 Comments

Your query expression probably isn't doing anything useful. Try just s.Average(a => a.Value)
What Jon Skeet meant was series.Average(a => a.Value).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.