If some method requires an ICollection<T>
as an argument, but I have only an IEnumerable<T>
available: Is it better to convert this IEnumerable<T>
to a IList<T>
or is it better to convert it to an array T[]
or shall I convert it to something else or is there no difference at all?
The IEnumerable<T>
is only required for this method call, so no further read/write/extend is required.
If you're not going to be accessing the elements, you should use ToList()
as explained why here.
If you'll be iterating through the elements, then it'd be better performance-wise to do it via an index (meaning casting them to an array), so that you can use a for loop
, instead of a foreach loop
.
for
is faster than your typical foreach
due to it using an index to access each element.