简体   繁体   English

linq sql-总数

[英]linq sql - aggregate count

I have some linq that returns the correct data. 我有一些返回正确数据的linq。

var numEmails = (from row in EmailBatchProposal  
where row.EmailBatchId == emailBatchId
select row.EmailBatchProposalId).Count();

However, if I understand linq correctly, this does not perform optimally. 但是,如果我正确理解了linq,这将无法达到最佳效果。 It grabs all the data and then walks through the list and counts the rows. 它获取所有数据,然后遍历列表并对行进行计数。 What I'd really like is for linq (in the background) to use like: 我真正想要的是linq(在后台)使用:

Select count(*) from ...

I trust the performance reasons are obvious. 我相信性能原因很明显。

Does anyone know the proper way to do this? 有人知道这样做的正确方法吗?

People generally learn best by practicing. 人们通常通过练习学习得最好。 I would suggest you get a copy of LinqPad (free), enter in your Linq query, and see what SQL it generates. 我建议您获得一个LinqPad副本(免费),在Linq查询中输入内容,并查看它生成的SQL。 Then you can modify the Linq query until you get exactly what you want. 然后,您可以修改Linq查询,直到获得所需的内容为止。

实际上,如果linq查询与实现IQueryable并支持转换为基础SQL变体的集合一起使用,则是正确转换示例中的Count函数的相当基本的功能。

You can just use the argument of .Count() . 您可以只使用.Count()的参数。

int numEmails = EmailBatchProposal.Count(x => x.EmailBatchId == emailBatchId)

As noted below, this doesn't actually resolve to any different SQL, but I think it's at least a cleaner looking alternative. 如下所述,这实际上并不能解析为任何其他SQL,但是我认为至少这是一种更简洁的选择。

Actually, the LINQ-to-SQL is smart enough to know that it should do a count... For example, if I have the following query: 实际上,LINQ-to-SQL非常聪明,足以知道它应该进行计数……例如,如果我有以下查询:

var v = (from u in TblUsers
        select u).Count();

the SQL that actually executes when I run this is: 运行此命令时实际执行的SQL是:

SELECT COUNT(*) AS [value]
FROM [tblUsers] AS [t0]

Amazing, huh? 太神奇了吧? Another poster made the really good suggestion of getting LinqPad - it is a WONDERFUL tool. 另一位发布者对获得LinqPad提出了非常好的建议-这是一个了不起的工具。 It will show you the exact SQL that gets executed. 它将向您显示执行的确切SQL。 You can always confirm with SQL profiler too. 您也可以始终使用SQL事件探查器进行确认。

Check the Log of the SQL used in the query. 检查查询中使用的SQL的日志。

        using (var dbc = new siteDataContext())
        {
            dbc.Log = Console.Out;
            var bd = (from b in dbc.birthdays
                     select b).Count();
            Console.WriteLine("{0}", bd);
        }

gives the query: 给出查询:

SELECT COUNT(*) AS [value]
FROM [dbo].[birthdays] AS [t0]
 -- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 3.5.30729.1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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