Does C# offer a way to create a list directly from an array without copying elements one-by-one?
I know that under-the-hood a list simply maintains an array, so it seems natural to start with an array and make a new list simply point to the array internally. The benefit of this would be tremendous gains in performance when converting array to List.
Is there a native way to do this in c#? If not, does anyone have an extension method or library to do this?
Peter asked for quantification of "tremendous gains in performance". So here it is based on my understanding of how List constructor works:
List() contains three overloads. One of the overloads takes IEnumerable as input. This overload works by declaring a new list of very small size (unless it has changed in a more recent build of c#, the historical default size is 0 and then initialized to 4 when an element is first added).
Each time an element is added to the the list, if the new element exceeds the capacity, then the array size is doubled by creating an entirely new array and copy elements one by one to the new array. The result of this is that the cost of building a List from an IEnumerable is O(n) PLUS the cost of all the array copies that occur. Point being, it's not small.
In the case of an IEnumerable, the List() construction must work this way because IEnumerable is of unknown size. If you were making a List from an array, you would know the exact size at creation time, which means the cost should be O(1).