IQueryable Vs IEnumerable in C#

IQueryable Vs IEnumerable – 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 contains only one method: GetEnumerator(). This method returns an IEnumerator object which we use 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. We call this 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 translates into a query language, such as SQL, and executed on the data source. IQueryable exists under System.Linq namespace.

IQueryable executes query 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.

Conclusion

In this article, we learned about IQueryable vs IEnumerable. 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