What is the difference between returning IQueryable vs. IEnumerable?

Technology CommunityCategory: LINQWhat is the difference between returning IQueryable vs. IEnumerable?
VietMX Staff asked 3 years ago
Problem

What is the difference between returning IQueryable<T> vs. IEnumerable<T>?

IQueryable < Customer > custs = from c in db.Customers
where c.City == "<City>"
select c;

IEnumerable < Customer > custs = from c in db.Customers
where c.City == "<City>"
select c;

Will both be deferred execution and when should one be preferred over the other?

The difference is that IQueryable<T> is the interface that allows LINQ-to-SQL (LINQ.-to-anything really) to work. So if you further refine your query on an IQueryable<T>, that query will be executed in the database, if possible.

Consider:

IQueryable<Customer> custs = ...;
// Later on...
var goldCustomers = custs.Where(c => c.IsGold);

That code will execute SQL to only select gold customers. On the other hand, will execute the original query in the database, then filtering out the non-gold customers in the memory:

IEnumerable<Customer> custs = ...;
// Later on...
var goldCustomers = custs.Where(c => c.IsGold);

This is quite an important difference, and working on IQueryable<T> can in many cases save you from returning too many rows from the database. Another prime example is doing paging: If you use Take and Skip on IQueryable, you will only get the number of rows requested; doing that on an IEnumerable<T> will cause all of your rows to be loaded in memory.