Difference between IQueryable and IEnumerable c#

Hi I will explain difference between IQueryable and IEnumerable list  in c# asp.net with example

IEnumerable

1. If we want to use IEnumerable in our application, we can get it by adding System.Collections namespace.

2. IEnumerable best suitable for in-memory operations because first it will execute “select query” on server and it will load all the data into client memory then only it will apply all the filter conditions .

Suppose if we have table called UserDetails in our database from that we need to get only top 3 records where users gender equals to “Male” for this if we use IEnumerable first it will execute “select query” on database server, it loads all the records into memory and then it filters the data based on our requirement.
3. For remote operations IEnumerable is not suggestable and its better use IEnumerable to perform query operations on in-memory collections like List, Array, etc.

In case if our tables contain more than 1 or 2 lac records then IEnumerable will fetch all the records into our application memory then it will perform filter conditions due to this our application becomes very slow.

4. IEnumerable is beneficial when you want to load all the data from query into memory and apply further filtering. Its best suitable for LINQ to Objects and LINQ to XML operations.

IEnumerable Example

IEnumerable<UserDetails> users= context.GetUsers();
var filterUser= users.Where(p => p.Gender== "Male");

Following is the very example for IEnumerable collection.

IQueryable

1. If we want to use IQueryable in our application, we can get it by adding System.Linq namespace.
2. IQueryable is best suitable for out-memory (remote database) operations because it will execute select query with all filter conditions on database server.

Suppose if we have table called UserDetails in our database from that we need to get only top 3 records where users gender equals to “Male” for this if we use IQueryable it will execute “select query along with filter conditions” and  records based on our conditions.
3. IQueryable is best suitable for LINQ to SQL operation

IQueryable Example

IQueryable<UserDetails> users= context.GetUsers();
var filterUser= users.Where(p => p.Gender== "Male");

below very simple example of IQueryable;

Leave a Reply

Your email address will not be published. Required fields are marked *