What is the difference between IQueryable, ICollection, IList and IDictionary
Loading
What is the difference between IQueryable, ICollection, IList and IDictionary
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Sachin SinghPosted Jun 27, 2022, 11:35 AM
Difference will be clear when you know where to use them and why.
There usage basically depends on 2 things
1. How much access of a collection you want to give to the consumer of your method.
2. Where do you want to filter the data (In-Memory after retreiving or directly inside the SQL Server engine)
Now, come to the point.
ICollection ---> Just Browse (Meaning whoever will consume the method/property with return type ICollection) will only be able to Browse the collection, meaning they are just allowed to use foreach loop on them.
IEnumerable---> Browse+Count (Meaning the consumer can apply foreach and can also use the Count() method to count the number of items)
IList ---> Almost full access to the collection (Browse + Count + Add + Remove+ Find)(Meaning the Consumer can apply foeach, can add items or even can delete items )
IQueryable--> Filtering will be on Sql Server engine. If you use any of the above collection and apply Where() linq method then it will first retrieve all data to the memory and will then do the filtering but with IQueryable you will only get the filtered data.
IDictionary --> As the name suggests if you want to find something based on the key then use Dictionary.
For example you want if you enter "IN" then it should return "India" similary "US" for "United States" the store it inside a dictionary
So, where to use what
1. If you are a Business layer developer then forget about everything and just use IEnumerable because you code will be used by UI asp.net developer meaning who consumes the code inside controller /aspx.cs. So they will never be allowed to add/remove data, they just need to iterate over the collection so better just give them IEnumerable. The UI devs will just pass the data they get from UI forms to the method you give them and adding /Updating validations will be on BLL method and final Add/Update will be on DAL method.
2. If you are a Data Access Developer then use combination of IQueryable and IEnumerable, as per the access level you want to give to BLL developer.
Inshort we rarely need IList or ICollection in a professional project.