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>
Maybe:
Enumerable.Empty<T>().AsQueryable();
Enumerable.Empty<T>().AsQueryable();
should do it.
Try return new T[0].AsQueryable();
Say you have an IQueryable<T>
called result
:
return result.Take(0);
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>()
Success story sharing
Union
queries to be broken up into multiple queries instead of one.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 .