IQueryable: Performance boost over remote Data Access
If we also follow the inheritance principle like OOPS programming, we need to extend our previous discussion “IEnumerable: Power behind Collections”. So this will lead us to write something about IQueryable.
What is an IQueryable Interface?
We can define it as functionality attached to an element which is used to evaluate queries against a known data source of unknown data type. It is available as
public interface IQueryable : IEnumerable
As we can see, it extends IEnumerable so we can easily say that all the inherent functionality of IEnumerable is available to IQueryable.
What is the difference?
IEnumerable works with in-memory collection. It is a read-only forward-only collection.
IQueryable works with remote data source.
Case 1 :If the case is to iterate through the in-memory collection, use IEnumerable,
Case 2 :if the case is to do any manipulation with the collection like Dataset, use IQueryable.
What are the properties available?
Provider : Points to the query provider that is associated with the data source like LINQ to SQL provider.
Expression: Points to a query expression which is associated with the instance of IQueryable that can be understood by the given query provider.
ElementType: Points to the type of the element(s) that are returned when the expression tree associated with this instance of IQueryable is executed.
IQueryable is not alone and comes as a package with IEnumberable. Enumeration causes the expression tree associated with an IQueryable object to be executed,but using IQueryable can save a lot of resources.
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, and one which returns an IQueryable. Say, for example, you have a Products table, and you want to get all of the products whose cost is >$25.
IEnumerable 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 the program. Program then filters the data. In essence, the database does a “SELECT * FROM Products”, and returns EVERY product.
With the right IQueryable provider,
IQueryable 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 a performance standpoint, It will only return 2 records across the network instead of 20,000