D
D
Dmitry2016-07-25 21:55:48
ASP.NET
Dmitry, 2016-07-25 21:55:48

Why IQueryable when IEnumerable?

Hello! Tell me, in one of the articles I came across an example

public IEnumerable<SomeValue> SomeMethod()
{
 return db.SomeValue.Select(item=>item);
}

and the example says that IQuerable is returned, I was confused, why IQuerable, when the return type is IEnumerable, won't IQuerable be cast to IEnumerable?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey, 2016-07-26
@senal

Strictly speaking, Select is an extension method and, depending on the object, can return both IEnumerable and IQueryable.
IQuerable "is" (inherits) IEnumerable, so in your example there is no casting as such, but the calling code cannot be sure that it was IQuerable (db.SomeValue.ToList().Select(item=>item); that was returned to it; and that's it changes).
You can return the base interface (you just need to look at why and why), and in this case, in the calling code, you can cast to IQueryable. But in general, not every IEnumerable can be cast to IQueryable.
The IEnumerable interface usually implements collections that store objects that have already been retrieved, while IQueryable objects that encapsulate queries. In the calling code, you can add conditions to IQueryable (Skip(), Take(), Where()) and the real request to the server will be subject to these conditions. But if you have already executed the request (ToList()) then all other operations will be on the client.
Imagine a table with a million records and think about the difference:
db.SomeValue.Select(item=>item).Take(100);
and
db.SomeValue.Select(item=>item).ToList().Take(100);

A
ar4ebaldello, 2016-07-26
@ar4ebaldello

IQueryable inherits IEnumerable . Those. in this example, we get the link up the hierarchy. This method will return us not an IQueryable or even an IEnumerable, but an object of some final class that implements these interfaces.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question