User Name:


User Email:




This information will only be saved for the purposes of communicating with those who have provided this information voluntarily regarding our services.We will never sell your name or email address to anyone.
© 2018 - First Crazy Developer (Abhishek Kumar)
  

crazydeveloper Difference Between IQueryable and IEnumerable in C#

Hello, in the previous article we discussed about importance of Collection in C# and today we will start discuss some important part of Collection. In order to understand the better approach of Collection we need to know about IQueryable, IEnumerable & IList.

Here we have most important question for C# developer - "How we can decide, which a better for our requirements is?"

We always 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.

The above question is important for us because to pick the right one is an important, by chance if we pick the wrong one will defiantly there is a performance impact in our application. All developer face this problem due to all these three option deal with the same situation in our programs.

Here first we need to know what exactly each one do in our programs then we can pick right one depends upon requirements.

Look at the following image:

In the above code we can see there is Super Interface IEnumerable with two Sub Interface IQueryable and IList. It means what can we do with IEnumerable can be used with IQueryable and IList with their specific add-on functionality. If we identify what are the specific add-on functionality with IQueryable and IList then will be easy to pick best one depends upon requirements.

Here we have an important question - "What is specific difference between them?"

Look at the following points:

IEnumerable: - When we to deal with in process memory object collections, and loop through the collection objects.

IQueryable: - When we have to run ad-hoc queries against data source like LINQ to SQL Server, Entity Framework and other sources.

IList: - When we have to add, remove or refer to an item by index.

We will understand the details concept of these above points in further discussion.

Look at the following code:

  1. public class SampleCode
  2. {
  3. private SanpleCodeAPPEntities db;
  4. public SampleCode()
  5. {
  6. db = new SanpleCodeAPPEntities();
  7. }
  8. public void EnumerableSampleCode()
  9. {
  10. IEnumerable<subscribed_user> user = db.subscribed_user.Where(us => us.User_Name.Contains("A"));
  11. var dummyuser = user.Take(1);
  12. Console.WriteLine("Total Enumerable Count=" + user.Count().ToString());
  13. }
  14. }
  15. class Program
  16. {
  17. static void Main(string[] args)
  18. {
  19. SampleCode sampleCode = new SampleCode();
  20. sampleCode.EnumerableSampleCode();
  21. Console.ReadLine();
  22. }
  23. }

In the above code we can see there is a method named- "EnumerableSampleCode". In this method we defined variable named "user" and important part we used IEnumerable data type for this variable. After this we create a LINQ query to get user date from subscribed user table where user name contains capital "A". In next line we get top one from that list and assign into dummyuser. Next we just print the total count of collection.

In main method we create an instance of SampleCode class named "sampleCode". In next line we call the EnumerableSampleCode method. Before we execute the above code we start SQL Server and start Activity Monitor to verify the LINQ query.

Look at the following image:

In the above image we can see how can we use Activity Monitor to track our LINQ query? Now we executed the above code and look into activity monitor.

Look at the following image:

In the above image we can see the exact SQL Query.

Look at the following SQL Query:

  1. SELECT
  2. [Extent1].[Id] AS [Id],
  3. [Extent1].[User_Name] AS [User_Name],
  4. [Extent1].[User_Email] AS [User_Email],
  5. [Extent1].[User_Contact] AS [User_Contact],
  6. [Extent1].[User_Address] AS [User_Address],
  7. [Extent1].[IsDeleted] AS [IsDeleted],
  8. [Extent1].[CreatedDate] AS [CreatedDate],
  9. [Extent1].[UpdatedDate] AS [UpdatedDate],
  10. [Extent1].[BlogTypeId] AS [BlogTypeId]
  11. FROM [dbo].[subscribed_user] AS [Extent1]
  12. WHERE [Extent1].[User_Name] LIKE N'%A%'

After all of the above discussion - "What we understood?"

If we analysed the above code and look line by line in the above SQL Query there is no Top keyword used. Means when we execute the above code the above SQL query executed and get all the table data and store into application memory. Now any further action will be worked on that.

Here we have an important question - "Why and when we have to use IEnumerable?"

IEnumerable<T> is used to iterate a read only collection. It has only one method GetEnumeartor() which allows you to iterate the read only collection using a foreach loop. It only iterates in the forward direction. It is a read only collection and even to find the number of objects in collection, we need to iterate through entire collection. We can't modify (Add or Remove) data IEnumerable bring ALL data from server to client then filter them, assume that you have a lot of records so IEnumerable puts overhead on your memory.

Next Question- When to use IEnumerable<T>?

  1. Working with the read only collection

  2. Need to read the objects in forward direction only

  3. Not concerned about thread safety

  4. Want to iterate the collection’s objects using foreach

 

After the above discussion we move ahead and make the small change into our previous code and replace the IEnumerable data type into IQueryable.

Here we will start discussion about IQueryable whenever we encounter to huge data with so many records so we have to reduce overhead from application. IQueryable prepares high performance in such situations (huge data) by filtering data firstly and then sending filtered data to client.

 

Look at the following code:

  1. namespace AbhishekBlogSampleCode
  2. {
  3. public class SampleCode
  4. {
  5. private SanpleCodeAPPEntities db;
  6. public SampleCode()
  7. {
  8. db = new SanpleCodeAPPEntities();
  9. }
  10. public void QueryableSampleCode()
  11. {
  12. IQueryable<subscribed_user> user = db.subscribed_user.Where(us => us.User_Name.Contains("A"));
  13. var dummyuser = user.Take(1);
  14. Console.WriteLine("Total Queryable Count=" + user.Count().ToString());
  15. }
  16. }
  17. }
  18. class Program
  19. {
  20. static void Main(string[] args)
  21. {
  22. SampleCode sampleCode = new SampleCode();
  23. sampleCode.QueryableSampleCode();
  24. Console.ReadLine();
  25. }
  26. }

In the above code we can see there is a method named- "QueryableSampleCode". In this method we defined variable named "user" and important part we used here IQueryable data type for this variable. If we compare the above code into this is small difference among them. Next line again we create a LINQ query to get user date from subscribed user table where user name contains capital "A". In next line we get top one from that list and assign into dummyuser and then print the total count of collection.

In main method we create an instance of SampleCode class named "sampleCode". If we compare the both code nothing difference rather than IQueryable instead of IEnumerable.

In next line we call the QueryableSampleCode method and again we start SQL Server and start Activity Monitor to verify the LINQ query. Now we executed the above code and look into activity monitor.

Look at the following image:

In the above image we can see the exact SQL Query.

Look at the following SQL Query:

  1. SELECT
  2. [GroupBy1].[A1] AS [C1]
  3. FROM ( SELECT
  4. COUNT(1) AS [A1]
  5. FROM ( SELECT TOP (1) [Extent1].[Id] AS [Id]
  6. FROM [dbo].[subscribed_user] AS [Extent1]
  7. WHERE [Extent1].[User_Name] LIKE N'%A%'
  8. ) AS [Limit1]
  9. ) AS [GroupBy1]

If we analysed the above code and look line by line in the above SQL Query there is optimized syntax which used in our application code. If we go through the application code look what we are doing here, first we filter the data as per user name next we get the first record of the filter data then we count the records. When we execute the above code the all above define expression in our code converted into SQL query then executed and get data. Now any further action will be worked on that.

In first example we look when we used IEnumerable the first line of the LINQ Query executed on the Sql Server and all data (it can be n numbers) store into inprocess memory, but when we used IQueryable first all code expression converted into SQL Query means wait till last expression then executed on SQL Server.

If we are fetching records from remote databases IQueryable<T> should be used. It constructs the query using an Expression Tree. On the other hand in the IEnumerable <T> the query is constructed using delegates. Both IQueryable<T> and IEnumerable <T> support lazy loading of data from remote database servers.

As we notice, the generated SQL has where clause and LINQ to SQL will (provider in this case) bring only filtered data from database. If we use IQueryable with foreach then query will be evaluated and executed at the same time.

Look at the following important points about IQueryable<T>:

  1. It implements IEnumerable <T> so the results can be iterated using foreach

  2. It is best suited to query against external data sources.

  3. It creates query using an Expression Tree

  4. It is used to query a queryable data source

 

Here again we have some an important question- "When to use IQueryable<T>?"

  Look at the following points:

    1. Working with the queryable datasource

    2. Need to apply filter on data at the datasource

    3. Need to apply paging, composition

    4. Working with external data source

    5. Needs to load data in deferred way

    6. Need to use foreach to iterate collection

 

Now after all of the above discussion I hope we understood the concepts of both and able to take decision to pick right one as per our requirements among IEnumerable and IQueryable.

 

Happy reading!! Smile

Abhishek Kumar


crazydeveloper Home Page 12 September 2015

Become a Fan