views:

57

answers:

3

In ADO.Net/SQLClient I would often do something like this:

SELECT COUNT(*) FROM SomeTable WHERE SomeKey = 1234

...and fire it using executescalar to return the value of count - for a simple check if something exists.

How would I do the same using LinqToSql?

+6  A: 
if (context.SomeTable.Any(row => row.SomeKey == 1234))
{
    DoStuff();
}

You could also use Count().

if (context.SomeTable.Count(row => row.SomeKey == 1234) > 0)
{
    DoStuff();
}

But this requires always to go through all rows while Any() can return after the first matching row - so Any() might have better performance.

Daniel Brückner
You're missing a right parenthesis in your code
Michael La Voie
Fixed ^^ (Noise to get at least 15 characters... ^^)
Daniel Brückner
You need a double equals to do a comparison `==`
Mykroft
Daniel Brückner
+3  A: 

Remember, Linq to Sql is deferred execution, which means, the query only actually executes when you access the collection. Therefore:

var q = (from p in db.SomeTable
        where p.SomeKey == 1234
        select p).Count();

Will turn into a SELECT Count() on the SQL side of things.

BFree
+2  A: 

If you're looking to see if something exists you can use the any function:

if (context.SomeTable.Any(i => i.SomeKey == 1234))
{
    return true;
}

or if you actually want to know that count you can use the where function and the count function:

context.SomeTable.Where(i=> i.SomeKey == 1234).Count();
Mykroft
You can move the predicate from Where() to Count() and save some typing.
Daniel Brückner
Good tip! Thanks.
Mykroft