JNYRanger
JNYRanger

Reputation: 7097

LINQ IQueryable Check if Empty without Enumerating

This might sound like a ridiculous question, but I couldn't find a straight answer anywhere.

I have a function that returns an IQueryable<MyObject> object from a LINQ-to-SQL query. I know that IQueryable objects utilize lazy evaluation, so I don't want to enumerate it by using .Count prior to returning the object. However, I would like to check that it is not "null" or empty prior to passing it back to the caller. The reasoning is that if the query returns no results it means the caller passed an invalid parameter, therefore I would like to throw an exception.

This question: LINQ results when there are no matches? didn't seem to provide a straight answer for my version of this question.

My question is: Is there a way to check if an IQueryable object is empty without enumerating it? Would checking against default(IQueryable<T>) do the trick?

Upvotes: 6

Views: 9233

Answers (2)

Servy
Servy

Reputation: 203817

Is there a way to check if an IQueryable object is empty without enumerating it?

No, that's impossible.

The only way to determine if the query has at least one result is to actually execute the query. You don't need to iterate the entire result set, but you need to try to fetch the first item, which means sending the query to the database, having it execute it, and send the response.

If it's really essential that you do this you're probably best off just pulling the entire result set into memory, into say a list, doing your check, and then returning an IEnumerable rather than an IQueryable.

That, or just don't do the check.

Upvotes: 5

gleng
gleng

Reputation: 6304

You could always use a .Any() in your LINQ statement prior to returning it. That way you will get a null value if your statement doesn't return anything.

Upvotes: 0

Related Questions