My question is really simple. When should I use List, IEnumerable and ArrayList.
Here’s my scenario. I’m working in a Web app using LINQ. Information is returned as a IEnumerable:
IEnumerable<Inventory> result = from Inventory i in db where....
I’m not sure how IEnumerable works, but every operation takes a lot of time to execute. More specifically, result.Count(), result.ElementAt(i), result.ToList, etc, each operation takes a considerable amount of time.
So, I was wondering if I should treat this as a List by doing result.ToList, instead of working with the IEnumerable variable.
Thanks!
If I understand what you’re doing correctly, you have a query like
from Inventory i in db select iand then you do several operations on the result:Now consider what happens when you have the query as different types:
IQueryable<T>The two lines above are the same. They don’t actually go to the database, they just create a representation of the query. If you have this,
Count()will execute an SQL query likeSELECT COUNT(*) FROM Inventory,ElementAt(5)will execute another query that takes only the fifth item in the table andToList()will execute something likeSELECT * FROM Inventory, but that’s what we want here.IEnumerable<T>Doing this again does not go the database, it only creates a representation of the query. But it’s a representation that can’t use the methods specific to
IQueryable<T>, so any LINQ operation will enumerate the collection, which will execute an SQL query likeSELECT * FROM Inventory.So, for the example:
Count()will execute theSELECT * …query only to count the items in the result.ElementAt(5)will execute the whole query again, only to throw away all items except for the fifth. AndToList()will execute the query one more time.List<T>This will actually execute the
SELECT * FROM Inventoryquery immediately and once. All operations you do withresultwon’t touch the database, they will be done in-memory.What should you take away from this? First, never use
IEnumerable<T>as the type of the database query. It has horrible performance.If you want to make several distinct operations on the result, using
IQueryable<T>might be the best solution.If you want to retrieve the whole result anyway, use
ToList()(orToArray()) as soon as possible and then work with the resultingList<T>.