The past week , I have been working on creating features in Tong Hin’s inventory module , and used many different types of collections interchangeably to retrieve data such as IEnumerable , ICollection , IList and IQueryable .
IEnumerable vs ICollection vs IList vs IQueryable
IEnumerable is the most basic type of list container to store data . It has no order and does not allow us to modify the set . An IEnumerable supports the where clause to filter elements , but it does not hold the count of elements as we need to iterate over the elements with “foreach” to get the count .
ICollection is a modifiable set and allows us to edit the elements in the collection with .Add , .Update and .Remove . Such as IEnumerable , ICollection also has no order and does not allow us to sort the data without changing it to a list with ToList() .
IList is an ordered set and provides an object indexer to allow the user to access the collection with square brackets like myList[x] . It is useful when we want to sort elements in the collection . I used it to sort dates to show the latest data in a table .
IQueryable is used when we want to run an Ad-hoc query , an Ad-hoc query is created to provide a specific record set from the database , usually defined to serve for a particular purpose . I used it to include different entities from other classes in one query .
In summary , each function has its own characteristics and is adaptable to different scenarios , and it is better for us not to memorize but understand how things work .
