IQueryable Vs IEnumerable in C#

Both IQueryable and IEnumerable are interfaces in .NET that represent a collection of objects. However, they have some important differences in how they work and when to use them. Let’s begin.

What is IEnumerable?

IEnumerable lets you iterate through a collection of objects. It only has one method that is defined: GetEnumerator(). This method returns an IEnumerator object that can be used to loop through the collection. IEnumerable exists under System.Collections namespace.

The elements of the collection are not retrieved until they are accessed, which means that any filtering, sorting, or projection has to be done in memory. This is referred to as “deferred execution.”

IEnumerable example with C# Code

ProductEntities prdent = new ProductEntities();
IEnumerable<Product> prd = prdent.Products;
IEnumerable<Product> prdResult = prd.Where(x => x.ProductCategory == 1).ToList<Product>();

What is IQueryable?

IQueryable extends IEnumerable and provides a more powerful way to query data from a data source. It defines methods that enable the creation of complex queries that can be translated to a query language, such as SQL, and executed on the data source. IQueryable exists under System.Linq namespace.

The queries are executed on the data source, which means that any filtering, sorting, or projection is performed on the data source rather than in memory. This is referred to as “deferred execution with server-side processing.”

IQueryable example with C# Code

ProductEntities prdent = new ProductEntities();
IQueryable<Product> prd = prdent.Products;
IQueryable<Product> prdResult = prd.Where(x => x.ProductCategory == 1).ToList<Product>();

Below image shows how, IQueryable and IEnumerable works while fetching data from RDBMS.

IQueryable vs IEnumerable

In the below video, you may see the major difference between IQueryable and IEnumerable while working with an RDBMS-like SQL server.

In general, you should use IEnumerable when working with in-memory data collections, and IQueryable when querying a data source such as SQL Server.

It’s also worth noting that IQueryable is more powerful but also has a higher overhead than IEnumerable, so it’s important to choose the appropriate interface for your scenario.

To summarize, When querying data from in-memory collections like List and Array, IEnumerable works best. On the other side, IQueryable is suitable for querying data from a remote database.

Please follow and like us:

Leave a Comment