Imagine I have a SearchService layer that has a method to search all cars starting with a certain string;
public static class Searcher{
public IAnInterface<Car> CarsStartingWith(string startWith){
//magic
}
}
What interface should my service use?
IQueryable can render for a nice fluid interface in the rest of my application.
IEnumerable has the lazy aspect going with it.
IList is just the most practical.
I would like to have all my services return the same interface for consistency makes the whole thing a lot easier.
ICollection could maybe be an option too, but it just offers so little...
You should use IList when you need access by index to your collection, add and delete elements, etc., and IEnumerable when you need just enumerate over your collection.
It depends on whether you wish to have any future queries performed on the entity and whether these should be in memory or not: If there are to be future queries and the DB should do the work return IQueryable. If there are to be future queries and it is to be done in memory return IEnumerable.
IEnumerable: IEnumerable is best suitable for working with in-memory collection (or local queries). IEnumerable doesn't move between items, it is forward only collection. IQueryable: IQueryable best suits for remote data source, like a database or web service (or remote queries).
IList doesn't support further filtering. IEnumerable exists in System. Collections Namespace. IEnumerable is a forward only collection, it can't move backward and between the items.
I would choose IEnumerable
because it has a more central place in the framework, providing versatility for those that need it, while also providing familiarity to those who are yet to get stuck into things like LINQ.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With