简体   繁体   中英

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.

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.

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(), ... };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM