[ACCEPTED]-When to use LINQ's .ToList() or .ToArray()-deferred-execution

Accepted answer
Score: 20

Unfortunately, I don't think there is a 31 good "hard and fast" rule here. It depends 30 a lot on how you expect the results to be 29 used, and what the query itself is actually 28 doing.

My initial thoughts are either any 27 expression that may be iterated more than 26 once or, to be safer in case potential iterations 25 are not obvious, any expression whose result 24 will never change.

In general, if you're 23 going to use the result of a query more 22 than once, it's always a good idea to store 21 it via ToList() or ToArray(). This is especially true if 20 you're LINQ query is an "expensive" one, as 19 it prevents the expensive operation from 18 running more than once.

Typically, if you're 17 only going to enumerate the results, then 16 I would leave it as IEnumerable<T>. If you plan to store 15 the results, or use the results more than 14 once, then storing it in a collection can 13 be beneficial.

The other place to watch for 12 is if you return the results in a public 11 API. While it's often nice to return IEnumerable<T>, depending 10 on the expected use case, you may want to 9 consider using ToList() to prevent the operation 8 from being executed more than once.

As for 7 whether to use ToList() or ToArray(), it really depends on 6 how you'll use the results. The cost associated 5 with each is nearly identical (ToList() actually 4 has slightly lower execution overhead if 3 the input is not ICollection<T>). Typically, I prefer 2 ToList() over ToArray() unless I have a specific need or 1 desire for an array.

Score: 3

ToList calls List<T>(IEnumerable<T>) constructor to create a List<T>, while 10 ToArrary uses an internal class Buffer<T> to grow the array.

If 9 the source collection (IEnumerable<T>) implements the 8 ICollection interface, the two methods use similar 7 code logic to copy the data.

ICollection.CopyTo(array, 0);  

Otherwise, ToList will 6 creates the List<T> dynamically. While ToArray copies 5 the element one by one into a new array. If 4 the array is full, the method doubles the 3 array size to hold the data. Finally the 2 method returns another array based on the 1 source collection’s size.

More Related questions