Thursday 2 May 2024

Difference between IEnumerable,IQueryable VS List

 First the difference between List<T>, IEnumerable<T> and IQueryable<T>.

 The content of List<T> will always be loaded into memory, because it uses an array in the background.


The content of IEnumerable<T> will only load the requested item into the memory. Compiler sets up a state machine during compiling a method with IEnumerable<T> that has a yield return T. So only one item at a time will be loaded into memory in this case.


IQueryable<T> is "special" version of IEnumerable<T>. Specifically designed to query data sources, and implemented by data providers. Like EF, NHibernate. So when you tell EF to fetch the data with .ToListAsync<T>() EF will only then go the database and execute the generated query. See the docs for more info about IQueryable<T>.