2

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.

Sebastian Werk
  • 1,204
  • 2
  • 13
  • 27
  • 1
    A fundamental difference is that `ICollection` allows adding and removing elements while `IEnumerable` does not. So yes, you will have to persist the enumerable as a concrete collection of some sort. – GSerg Aug 16 '19 at 11:48
  • I am aware of this difference, but I do not know, if it is better to convert it to `T[]` instead of `IList` or the other way around. – Sebastian Werk Aug 16 '19 at 11:56
  • in your case, i think it does not matter which one you choose – Barış Akkurt Aug 16 '19 at 11:57

1 Answers1

1

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.

SpiritBob
  • 1,311
  • 8
  • 35