To create and initialize an array with another array I currently do this:
void Foo( int[] a )
{
int[] b = new int[ a.Length ];
for ( int i = 0; i < a.Length; ++i )
b[ i ] = a[ i ];
// Other code ...
}
Is there a shorter or more idiomatic way of doing this in C#?
It will be great if this can be done in a single statement, like in C++:
vector<int> b( a );
If this cannot be done in a single statement, I will take what I get 🙂
I like using LINQ for this:
That being said, Array.Copy does have better performance, if this will be used in a tight loop, etc:
Edit:
The C# version of this would be:
List<T>is C#’s equivalent tostd::vector<T>. The constructor above works with anyIEnumerable<T>, including anotherList<T>, an array (T[]), etc.