Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cheapest way to copy an IEnumerable<T>?

Tags:

c#

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?

like image 463
mpen Avatar asked Dec 31 '10 04:12

mpen


People also ask

How do I get a count of IEnumerable?

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.

What is IEnumerable in C#?

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.


1 Answers

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.

like image 154
mmx Avatar answered Oct 10 '22 23:10

mmx