What is the difference between IEnumerable and IQueryable in C#?

CsharpServer Side ProgrammingProgramming

  • IEnumerable exists in System.Collections Namespace.
  • IQueryable exists in System. Linq Namespace.
  • Both IEnumerable and IQueryable are forward collection.
  • IEnumerable doesn’t support lazy loading
  • IQueryable support lazy loading
  • Querying data from a database, IEnumerable execute a select query on the server side, load data in-memory on a client-side and then filter data.
  • Querying data from a database, IQueryable execute the select query on the server side with all filters.
  • IEnumerable Extension methods take functional objects.
  • IQueryable Extension methods take expression objects means expression tree.

Example

IEnumerable

dbContext dc = new dbContext ();
IEnumerable
<SocialMedia>
list = dc.SocialMedias.Where(p => p.Name.StartsWith("T"));
list = list.Take<SocialMedia>(1);
</SocialMedia>

Sql statement generated for the above query

SELECT [t0].[ID], [t0].[Name] FROM [SocialMedia] AS [t0]
WHERE [t0].[Name] LIKE @p0

IQueryable

dbContext dc = new dbContext ();
IQueryable<SocialMedia> list = dc.SocialMedias.Where(p => p.Name.StartsWith("T"));
list = list.Take<SocialMedia>(1);

Sql statement generated for the above query

SELECT top 1 [t0].[ID], [t0].[Name] FROM [SocialMedia] AS [t0]
WHERE [t0].[Name] LIKE @p0
raja
Published on 05-Aug-2020 08:42:34
Advertisements