ReSharper suggested to enumerate an IEnumerable<T> to a list or array since I had “possible multiple enumerations of IEnumerable<T>“.
The automatic code re-factoring suggested has some optimization built in to see whether IEnumerable<T> already is an array before calling ToArray().
var list = source as T[] ?? source.ToArray();
- Isn’t this optimization already built-in the original LINQ method?
- If not, what would be the motivation not to do so?
Nope, there is no such optimization. If source is
ICollection, then it will be copied to new array. Here is code ofBuffer<T>struct, which used byEnumerableto create array:And here is
Enumerable.ToArray()method: