IEnumerable and IQueryable may seem like the same at a quick glance, but there are important differences that us, as developers must be aware so that we not only get a working product out the door but also something that performs well.

What is IEnumerable?

Simply put, is something that let’s you go from one element of your collection over to the next (an interface that will provide you with an iterator that moves forward), an example of how you can declare and use IEnumerable is as follow:

As long as you are using a type that implements IEnumerable you will have the advantage of being able to iterate over your collection.

When can I use IEnumerable?

  • When you want to iterate over a collection (List, Arrays, etc.)
  • When you want to get all the results from your query and apply any further filtering once your collection has been loaded in memory.
  •  When you are using LINQ to XML or LINQ to Object.

What is IQueryable?

IQueryable is an interface that implements IEnumerable (and because it implements IEnumerable it means that it allows you to iterate over a collection plus some more)

IQueryable takes Expression objects instead of delegates (which is what IEnumerable takes)

When can I use IQueryable?

  •  When you want to iterate over a collection (same as IEnumerable)
  • When you want to work with data from out-memory, such as a database, a web service etc
  • When you want to apply a filter to your query BEFORE the query is executed (this can save you heaps of resources)
  • When Lazy loading is needed (you only get what you need, not the entire list of records)

So… What’s is the main difference between IEnumerable and IQueryable ?

The main difference is that with IEnumerable you get all the records at once while with IQueryable you only get the records that you want, let’s see that in action with an example:

Let’s assume that you have a client table with all your client’s information (approximately 1000 clients)

  • If you use IEnumerable to get the first 5 customers you end up loading all 1000 and then selecting the first 5.
  • With IQueryable you only select the first 5 (saving a lot of resources !)

For some other useful resources you can check out some stack overflow answers and this dotnet-trick’s article on IEnumerable vs IQueryable

 

Thank you for reading, I hope you have now a clearer idea of IEnumerable and IQueryable and when each of them can be used best.