ChatGPT解决这个技术问题 Extra ChatGPT

Enumerable.Empty<T>() equivalent for IQueryable

When a method returns IEnumerable<T> and I do not have anything to return, we can use Enumerable.Empty<T>().

Is there an equivalent to the above for a method returning IQueryable<T>


T
Tim Cooper

Maybe:

Enumerable.Empty<T>().AsQueryable();

I know, currently that is the only simple, direct & dirty ;-) solution
Unfortunately that doesn't create an actual empty IQueryable, which means it causes e.g. Union queries to be broken up into multiple queries instead of one.
@NetMage That's right. What is more confusing is that your code don't break in the line where is Union, but probably when you try something after this. This answer is accepted and voted but it can be very misleading. @Sunny Please consider to edit your answer. Answer in this question helped me: Enumerable.Empty<T>().AsQueryable(); This method supports the LINQ to Entities infrastructure and is not intended to be used directly from your code .
P
Paul Fleming

Enumerable.Empty<T>().AsQueryable(); should do it.


b
bdukes

Try return new T[0].AsQueryable();


@Nauman - you actually create an [empty] T array - no new object of T is actually created.
P
Protector one

Say you have an IQueryable<T> called result:

return result.Take(0);

J
Josh

I would advise against alejandrobog's answer as this will still use memory to create an empty array.

Array.Empty<T>().AsQueryable();

or

Enumerable.Empty<T>().AsQueryable();

are preferred. Array.Empty will allocate a static typed array so only one empty array of T is created and that is shared amongst all Empty queryables.


Array.Empty<T> is only available after .NET Framework 4.6. For earlier versions, you can use new object[0].Cast<T>()