140

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>

Numan
  • 3,918
  • 4
  • 27
  • 44

6 Answers6

221

Maybe:

Enumerable.Empty<T>().AsQueryable();
Sunny
  • 6,286
  • 2
  • 25
  • 27
  • 2
    I know, currently that is the only simple, direct & dirty ;-) solution – Numan Apr 23 '10 at 11:04
  • 10
    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 May 22 '17 at 23:11
  • 1
    @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().AsQueryable(); This method supports the LINQ to Entities infrastructure and is not intended to be used directly from your code](https://stackoverflow.com/questions/37815309/enumerable-emptyt-asqueryable-this-method-supports-the-linq-to-entities-i) . – Lazar Đorđević May 19 '21 at 20:09
35

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

Paul Fleming
  • 24,238
  • 8
  • 76
  • 113
Josh
  • 68,005
  • 14
  • 144
  • 156
7

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

bdukes
  • 152,002
  • 23
  • 148
  • 175
alejandrobog
  • 2,091
  • 14
  • 20
7

Say you have an IQueryable<T> called result:

return result.Take(0);
Protector one
  • 6,926
  • 5
  • 62
  • 86
5

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.

Josh
  • 289
  • 3
  • 10
  • `Array.Empty` is only available after .NET Framework 4.6. For earlier versions, you can use `new object[0].Cast()` – TZU Dec 20 '19 at 21:13
1

Enumerable.Empty().AsQueryable(); is wrong since Union will break and wont work. Workaround is

var db = new DbContext();
var query = db.Set<T>().Take(0);

valentasm
  • 2,137
  • 23
  • 24
  • Take(0) is the right approach. The Empty() way also breaks Concat, and probably any other method that tries to build on the empty queryable. – Mark Smith Dec 12 '22 at 22:30