What is the best way to convert from a generic IEnumerable<T> implementation to an array of T? The current solution I have looks like the following:
IEnumerable<string> foo = getFoo(); string[] bar = new List<string>(foo).ToArray();
The transfer through a List<T> seems unneccesary, but I haven’t been able to find a better way to do it.
Note: I’m working in C# 2.0 here.
.NET 3.0 and after:
Call the
ToArrayextension method onIEnumerable<T>, it does nearly the same as below, performing type sniffing and some other optimizations..NET 2.0 and before:
Generally speaking, using a
List<T>which will be initialized with theIEnumerable<T>and then callingToArrayis probably the easiest way to do this.The constructor for
List<T>will check theIEnumerable<T>to see if it implementsICollection<T>to get the count of items to properly initialize the capacity of the list. If not, it will expand as normal.Of course, you might end up creating a number of
List<T>instances just for the purpose of transformingIEnumerable<T>toT[]. To that end, you can write your own method, but you would really just be duplicating the code that exists inList<T>already.