469,922 Members | 2,106 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,922 developers. It's quick & easy.

finding out if a linq table has 0 rows

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?

Nov 19 '08 #1
2 3619
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)

Andy B wrote:
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?
Nov 20 '08 #2
"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.
Nov 20 '08 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

4 posts views Thread by BeSharp | last post: by
8 posts views Thread by Andy | last post: by
1 post views Thread by ph_haenggi | last post: by
4 posts views Thread by =?Utf-8?B?RXJpYyBGYWxza2Vu?= | last post: by
21 posts views Thread by hrishy | last post: by
3 posts views Thread by =?Utf-8?B?UGF1bCBQcmV3ZXR0?= | last post: by
2 posts views Thread by jelle79 | last post: by
reply views Thread by Waqarahmed | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.