C# Interview Question #123

What is the difference between ToList(), ToArray(), and AsEnumerable()?

Advanced LINQ, Expressions & Collections Senior Advanced

Quick Interview Answer

ToList() immediately enumerates a sequence and stores the results in a List<T>. ToArray() also materializes immediately but stores the results in an array.

Detailed Explanation

ToList() immediately enumerates a sequence and stores the results in a List<T>. ToArray() also materializes immediately but stores the results in an array.

AsEnumerable() does not normally materialize the data. It exposes the sequence as IEnumerable<T>. With IQueryable<T>, calling AsEnumerable changes subsequent LINQ processing from provider-based query translation to LINQ-to-Objects.

This distinction is important in EF Core. Calling AsEnumerable too early can cause later filtering or transformation to happen in application memory instead of in the database.

Code Example

var list = query.ToList();
var array = query.ToArray();

var clientSequence = query.AsEnumerable();