Skip to main content

C#: Understand about IEnumerable vs. IQueryable vs. ICollection vs. IList

In this article we’ll understand about the interfaces (IEnumerable, IQueryable, ICollection and IList) available for holding and querying the data.

IEnumerable: 
·         IEnumerable exists in System.Collections Namespace.
·         IEnumerable is most generic item of all and a core interface which is used to iterate over collection of specified type.
·         IEnumerable provides Enumerator for accessing collection.
·         IEnumerable is forward only collection likes LinkedList. It doesn’t move between items or backward, i.e. one can't get at fifth item without passing first four items.
·         It is read-only collection and it doesn't support add or remove items.
·         IEnumerable is best to query data from in-memory collections like List, Array etc.
·         It mainly implements two methods:
o   MoveNext: This method tells whether there are more records to move on or not.
o   GetCurrent: This method returns the current record from the collection.
·         IEnumerable still might use deferred execution and also supports further filtering.
·         IEnumerable does not run query until it is requested by iteration or enumerator.
·         Using IEnumerable we can find out the no of elements in the collection after iterating the collection.

IQueryable: 
·         IQueryable exists in System.Linq namespace.
·         IQueryable extends IEnumerable interface.
·         IQueryable allows deferred query execution i.e. query generated through IQueryable isn't executed until you iterate, enumerate or add .ToList() method.
·         IQueryable enables a variety of interesting deferred execution scenarios such as paging and composition based queries.
·         IQueryable best suits for remote data source, like a DB or web service.
·         IQueryable is particularly used for LINQ queries.
·         IQueryable doesn’t support custom comparer, like any sting method such as ‘string.IsNullOrWhiteSpace’ etc.
·         IQueryable is not a good place to handle errors, so one must take care while writing complex queries.

ICollection: 
·         ICollection exists in System.Collections Namespace.
·         ICollection implements IEnumerable interface.
·         ICollection is base of Collection<T>, IList<T> and IDictionary objects.
·         It is considered the most basic type for collections and used to manipulate generic collections.
·         As it implements IEnumerable interface so it’s also implements methods MoveNext and GetCurrent, so with this interface you can iterate through collection.
·         ICollection also having its own methods (apart from IEnumerable methods) like:
o   Add: It adds record at the end of collection
o   Remove: It removes specified item from collection
o   Contains: It’s a boolean type method which tells whether collection contains the specified item or not.
·         Some collections that limit access to their elements, i.e. Queue or Stack class, directly implement the ICollection interface.
·         ICollection is normally used where we define EF table relationships and we use this in virtual keyword.
·         ICollection doesn’t support indexing like IList does.

IList: 
·         IList exists in System.Collections Namespace.
·         IList implementations fall into three categories:
o   Read-only: A read-only IList cannot be modified.
o   Fixed-size: A fixed-size IList does not allow the addition or removal of elements, but it allows the modification of existing elements.
o   Variable-size: A variable-size IList allows the addition, removal and modification of elements.
·         IList is used where you need to iterate (read), modify and sort, order a collection
·         With IList random element access is allowed i.e. you can access an element in a specific index in a list. For e.g. you can directly access an element at index 10 instead of first iterating through 0-9 elements.
·         Like IEnumerable, IList is also in memory collection and helps you to query data from in-memory collections like List, Array etc.
·         IList implements two interfaces ICollection and IEnumerable. So it’s also implements the methods of the both the interfaces.
·         IList also having its own methods like:
o   Insert: It insert the given item at specified Index.
o   RemoveAt: It removes the item from specified Index.
o   IndexOf: It retrieves the item from specified Index.
·         IList can give you the no of elements in the collection without iterating the collection.
·         IList supports deferred execution, but it doesn't support further filtering.
·         IList supports custom comparer as comparison is done inside the memory.

Summary
In this post I tried to explain some of the basic difference between IEnumerable, IQueryable, ICollection and IList interfaces. I hope this article will help you to choose specific interface based on your demand. You can share your feedback, question or comments about this article.

Comments

  1. Nice article. I would also add List explanation here

    ReplyDelete

Post a Comment

Popular posts from this blog

Error 405 : ASP.NET Core Web API PUT and DELETE Methods not allowed

Recently, while working with .Net core API I came across the issue of “Error 405 — Methods not Allowed” After some research, I found out that both GET and POST requests working fine but neither PUT nor DELETE requests working. Another thing is that the PUT and DELETE request was also working fine on my local machine but failed when we host on our Azure server. When I explored the issue on the web it led me to the conclusion that WebDAVModule seems to set PUT and DELETE request methods disabled by default and due to that PUT and DELETE throw 405 errors. To make the PUT and DELETE requests work, we need to override the WebDAVModule setting in web.config file by adding the below settings under “ system.webServer ”. < system.webServer >   < modules runAllManagedModulesForAllRequests = " false " >     < remove name = " WebDAVModule " />   </ modules > </ system.webServer > There may be 2 web.config files in your

C#: Merging Excel cells with NPOI HSSFWorkbook

In this post we’ll see how to merge the two or more cell with each other while creating the excel sheet using NPOI . Mentioned below is code to merge multiple cells, in this example we are merging first cell to fifth cell of first row (you can adjust row or cell range by passing particular parameters in CellRangeAddress). //Created new Workbook var hwb = new NPOI.HSSF.UserModel. HSSFWorkbook (); //Create worksheet with name. var sheet = hwb.CreateSheet( "new sheet" ); //Create row and cell. var row = sheet.CreateRow(0); var cell = row.CreateCell(0); ; //Set text inside cell cell.SetCellValue( "This is Merged cell" ); cell.CellStyle.WrapText = true ; //define cell range address // parameters: -> first row to last and first cell to last cell var cra = new NPOI.SS.Util. CellRangeAddress (0, 0, 0, 4); //Add merged region to sheet. sheet.AddMergedRegion(cra); Hope this solution helps you J

How to set Swagger as the default start page for API hosted on the Azure web app?

I created an Asp.Net Core 2.x Web API and configured Swagger on it, below is the code added in Configure method under Startup.cs file, for full swagger configuration, check here //Add swagger configuration app.UseSwagger(); app.UseSwaggerUI(c => {     c.SwaggerEndpoint( "../swagger/v1/swagger.json" , "Test API V1" ); }); On my local machine when I run the API it is automatically redirected to the Swagger page. However, when I hosted this API as an Azure web app it is not redirecting directly to the Swagger and to access the swagger, I had to append /swagger in the URL, for example, https://testapi.azurewebsites.net/swagger/ Solution: Set RoutePrefix to string.Empty under app.UseSwaggerUI like below: app.UseSwaggerUI(c => {     c.SwaggerEndpoint( "../swagger/v1/swagger.json" , "Test API V1" );      c.RoutePrefix = string .Empty; // Set Swagger UI at apps root }); And that’s it, now when you brows