I would like to execute a Linq to Sql statement that captures the count and average in a (filtered) set of data. What I have works, but it requires two queries to the database when it should be possible in one query.
Interestingly enough, I can get one query to be emitted when I use a group by clause.
For example:
select count(*), avg(duration) from events
My linq looks like this:
var x = from e in db.events
select e;
x = from i in x
where i.NAME == "foo"
select i;
return new {
count = x.Count(),
avgDuration = x.Average(e => e.Duration)
};
With that code I get two queries:
SELECT AVG([t0].[DURATION]) AS [value] FROM [dbo].[EVENTS] AS [t0]
and
SELECT COUNT(*) AS [value] FROM [dbo].[EVENTS] AS [t0]
Is there another way?