Menu Close

IEnumerable Vs IQueryable in C#


In this article we will learn about IEnumerable Vs IQueryable in C#. Please read our previous article Difference Between IEnumerable, ICollection And IList.

IEnumerable 

IEnumerable is best suitable for working with in-memory collection (or local queries). IEnumerable doesn’t move between items, it is forward only collection.

IQueryable 

The major difference is that IEnumerable will enumerate all elements, while IQueryable will enumerate elements, or even do other things, based on a query. In case of IQueryable Linq Query get used by IQueryProvider  which must interpret or compiled in order to get the result.

i.e Extension methods defined for IQueryable take Expression objects instead of Fun objects (which is what IEnumerable uses)., meaning the delegate it receives is an expression tree instead of a method to invoke.

IEnumerable is great for working with in-memory collections, but IQueryable allows for a remote data source, like a database or web service.

Many  developers gets confused between IEnumerable and IQueryable. When it comes to writing code, both looks very similar. However there are many difference between them which needs to be taken care of while writing code. Both have some intended usability scenarios for which they are made.

Below lists the differences between them based on their properties :

IEnumerableIQueryable
NamespaceSystem.Collections NamespaceSystem.Linq Namespace
Derives fromNo base interfaceDerives from IEnumerable
Deferred ExecutionSupportedSupported
Lazy LoadingNot SupportedSupported
How does it workWhile querying data from database, IEnumerable execute select query on server side, load data in-memory on client side and then filter data. Hence does more work and becomes slow.While querying data from database, IQueryable execute select query on server side with all filters. Hence does less work and becomes fast.
Suitable forLINQ to Object and LINQ to XML queries.LINQ to SQL queries.
Custom QueryDoesn’t supports.Supports using CreateQuery and Execute methods.
Extension mehtod ParameterExtension methods supported in IEnumerable takes functional objects.Extension methods supported in IEnumerable takes expression objects i.e. expression tree.
When to usewhen querying data from in-memory collections like List, Array etc.when querying data from out-memory (like remote database, service) collections.
Best UsesIn-memory traversalPaging

References

Microsoft C#

Conclusion

In this article we will learn about IEnumerable Vs IQueryable in C#.


Leave a Reply

Your email address will not be published.