frenchie
frenchie

Reputation: 51927

linq to sql where clause and counting

I have a linq-to-sql query that I use to fill an object that has ints as properties and whose function is to hold counts.

The query looks like this (for now)

var TheQuery = from.....
               where ....
               in thefilteredresults
               select new MyModel()
               {
                   Total = thefilteredresults.Count(),

                   TotalTime = (from x in thefilteredresults
                                where x.Outcome == 4).Sum(t => t)
               }.Single();

I'm have some problem filtering first and then counting based on the filtered results of the initial where clauses. What do I need to modify?

Thanks.

Upvotes: 4

Views: 1508

Answers (2)

usr
usr

Reputation: 171178

You can hack this together:

(from x in table
where filter(x)
group x by 0 into g
select new { Count = (int?)g.Count() ?? 0, Sum = (int?)g.Sum(x => x.Value) ?? 0 }).Single()

SQL Server will optimize out the unneeded grouping. It is probably best do document why you wrote it like this.

Edit: I included a strange-looking cast to int?. The reason for this is to tell Linq to SQL to assume that the value is nullable and to use a COALELCE function call to convert the NULL to 0. This is a hack that should be documented, too.

Upvotes: 5

StriplingWarrior
StriplingWarrior

Reputation: 156469

Since you're really only looking for one result, this is probably the simplest approach:

var filteredResults = from ....
                      where ....
                      select ....;
var myModel = new MyModel{ Total = filteredResults.Count(), ... };

Upvotes: 1

Related Questions