Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What interface should my service return? IQueryable, IList, IEnumerable?

Tags:

c#

.net

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...

like image 612
Boris Callens Avatar asked Mar 25 '09 14:03

Boris Callens


People also ask

Should I use IList or IEnumerable?

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.

Should I repository return list or IEnumerable?

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.

Should I use IQueryable or 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).

What is difference between IList and IEnumerable?

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.


1 Answers

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.

like image 180
Jeff Yates Avatar answered Sep 19 '22 16:09

Jeff Yates