views:

41

answers:

2

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;
    }

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

+1  A: 

You could express it quite a bit shorter like this:

return taxidb.Registrations.Any(r => r.EmailId == emailId && r.Password==password);
klausbyskov
@klausbyskov so you think Any() would be more suitable..
Pandiya Chendur
@Pandiya Chendur I doubt that you will see any performance difference between `Any()` and `Count() == 0`. After all the generated sql statement will **have** to check if there is a record one way or the other.
klausbyskov
But in regards to humans reading the code? It's definitely simpler to understand if it says `return whether there's any user with this email and pass` instead of `return whether the number of users with this email and pass is not 0`.
ANeves
@klausbyskov: As Mike pointed out, the SQL generated by `Count` vs `Any` **will** be different.
R0MANARMY
@R0MANARMY yes, different, but I doubt they have different execution plans.
klausbyskov
+1  A: 

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

Here's what it will be:

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]

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.

Mike