finding out if a linq table has 0 rows

  • Thread starter Thread starter Andy B
  • Start date Start date
A

Andy B

How would you find out if a linq table has 0 rows in it? I have this code:

NewsContext.V_News() '*** linq table to be tested for 0 rows

Any ideas?
 
linq to sql queries are only executed when you foreach the results. as a
datareader is used the row count is not known until all rows are read.
so the easiest is convert the query to an array. you then have both the
data and the row count (array size) at that point.

if you just need a row count, then don't use linq, as it has to read all
the rows and count them. add a method to the context that uses a
sqlcommand and count(*) to get the rowcount. sqlserver in this case will
do the count much faster.

note- in linq to sql, every time you foreach the query, its run again

-- bruce (sqlwork.com)
 
"linq to sql queries are only executed when you foreach the results."
IEnumerable. Makes sense.

"as a datareader is used the row count is not known until all rows are
read."
Does linq make extensive use of dataReader internally?

"so the easiest is convert the query to an array."
Will keep it in mind for later if I need it.

"you then have both the data and the row count (array size) at that point."
Good way to do it if you need the results and the count. Doesn't linq have
something like this:
'*** query the v_news linq table
NewsContext.CreateQuery("select count(*) from v_news")

"if you just need a row count, then don't use linq, as it has to read all
the rows and count them. add a method to the context that uses a sqlcommand
and count(*) to get the rowcount. sqlserver in this case will do the count
much faster."
I think I will use this instead. Just trying to prevent a trip to the server
just for that.

"note- in linq to sql, every time you foreach the query, its run again"

Except when using data functions that are linked to sql procedures and
functions.
 
Back
Top