查询结果我应该使用Count()或Any() [英] query result what should i use Count() or Any()

查看:693
本文介绍了查询结果我应该使用Count()或Any()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过此存储库方法检查用户的登录信息。

I am checking login of a user by this repository method,

  public bool getLoginStatus(string emailId, string password)
    {
        var query = from r in taxidb.Registrations
                    where (r.EmailId == emailId && r.Password==password)
                    select r;
        if (query.Count() != 0)
        {
            return true;
        }
        return false;
    }

我在前面的问题之一! .Any()会更快...我应该使用哪个?任何建议....

I saw in one of the previous questions !query.Any() would be faster... Which should i use? Any suggestion....

推荐答案

生成的sql将在两个调用之间不同。您可以通过将context.Log属性设置为Console.Out或某事来检查。

The sql generated will be different between the two calls. You can check by setting your context.Log property to Console.Out or something.

这将是:

SELECT COUNT(*) AS [value]
FROM [dbo].[Registrations] AS [t0]
WHERE [t0].[EmailId] = @p0 and [t0].Password = @p1

SELECT 
    (CASE 
        WHEN EXISTS(
            SELECT NULL AS [EMPTY]
            FROM [dbo].[Registrations] AS [t0]
            WHERE [t0].[EmailId] = @p0 and [t0].Password = @p1
            ) THEN 1
        ELSE 0
     END) AS [value]



在这种情况下,我怀疑它会有什么区别,因为EmailID可能一个唯一索引所以只能有1个结果。在另一种情况下,count可以> 1,Any将是更可取的,因为第二个查询允许sql server短路搜索,因为它只需要找到一个证明任何存在。

In this case, I doubt it will make any difference because EmailID is probably a unique index so there can only be 1 result. In another case where count can be > 1, Any would be preferable because the second query allows sql server to short circuit the search since it only needs to find one to prove that any exist.

这篇关于查询结果我应该使用Count()或Any()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆