I've got an IEnumerable<T>
, and I need a copy of it. Anything that implements IEnumerable<T>
will do just fine. What's the cheapest way to copy it? .ToArray()
maybe?
IEnumerable has not Count function or property. To get this, you can store count variable (with foreach, for example) or solve using Linq to get count.
IEnumerable is an interface defining a single method GetEnumerator() that returns an IEnumerator interface. It is the base interface for all non-generic collections that can be enumerated. This works for read-only access to a collection that implements that IEnumerable can be used with a foreach statement.
ToArray
is not necessarily faster than ToList
. Just use ToList
.
The point is as long as you don't know the number of elements of the original sequence before enumerating, you end up with resizing an array and adding elements to it like a List<T>
does, so ToArray
will have to do the same thing a List<T>
does anyway. Besides, ToList
gives you a List<T>
and that's nicer than a raw array.
Of course, if you know the concrete type of the IEnumerable<T>
instance, there can be faster methods, but that's not germane to the point.
Side note: using an array (unless you have to) is arguably a micro-optimization and should be avoided most of the time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With