How to do aggregation without "group by" in Linq?

Everything I can find on linq for aggregation has a "group by" clause. How do I write this query in LINQ? I have a list of pairs of date values ​​and I want to take the average:

SELECT AVG(MySuff.Value) AS AvgValue FROM MyStuff

      

0


source to share


6 answers


Answer to modified example (I believe):



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

      

+1


source


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


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


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


Bit sorter

pairs.Average(a=>a.Value)   

      

If there is no join, group or let, Query Expressions (from ...) is not worth it in my opinion.

+1


source


Thanks everyone for the help. Here's what I figured to work.

(from s in series select s).Average( a => a.Value )

      

Regards, Alan ... R

0


source







All Articles