When a method returns IEnumerable<T>
and I do not have anything to return, we can use Enumerable.Empty<T>()
.
Is t开发者_Go百科here 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.
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);
精彩评论