LINQ - Need concept regarding IQueryable & IEnumerable

Asked By Tridip Bhattacharjee on 06-Jul-12 03:06 AM

i never use LINQ. so first i need to know the keyword  IQueryable & IEnumerable is related with LINQ or Entity Framework.

please discuss about what is  IQueryable & what is IEnumerable

Public IQueryable<Product> GetAll()
{
 return _products.AsQueryable();
}

what does it mean IQueryable<Product>.
we can write like IList<Product> instead??

what is the advantage of  IQueryable.
when i should use IQueryable  and when IEnumerable....please come with small sample code.
what is the main difference between IQueryable  and IEnumerable.

thanks

Somesh Yadav replied to Tridip Bhattacharjee on 06-Jul-12 05:18 AM

Marc Gravell's http://stackoverflow.com/questions/1578778/using-iqueryable-with-linq/1578809#1578809 answer is very complete, but I thought I'd add something about this from the user's point of view, as well...

The main difference, from a user's perspective, is that, when you use IQueryable<T> (with a provider that supports things correctly), you can save a lot of resources.

For example, if you're working against a remote database, with many ORM systems, you have the option of fetching data from a table in two ways, one which returns IEnumerable<T>, and one which returns an IQueryable<T>. Say, for example, you have a Products table, and you want to get all of the products whose cost is >$25.

If you do:

 IEnumerable<Product> products = myORM.GetProducts();
 var productsOver25 = products.Where(p => p.Cost >= 25.00);

What happens here, is the database loads all of the products, and passes them across the wire to your program. Your program then filters the data. In essense, the database does a "SELECT * FROM Products", and returns EVERY product to you.

With the right IQueryable<T> provider, on the other hand, you can do:

 IQueryable<Product> products = myORM.GetQueryableProducts();
 var productsOver25 = products.Where(p => p.Cost >= 25.00);

The code looks the same, but the difference here is that the SQL executed will be "SELECT * FROM Products WHERE Cost >= 25".

From your POV as a developer, this looks the same. However, from a performance standpoint, you may only return 2 records across the network instead of 20,000... from stackoverflow


Tridip Bhattacharjee replied to Somesh Yadav on 07-Jul-12 02:00 PM
thanks