Initializing a C# array with multiple copies of the same element

后端 未结 5 1743

In the C++ Standard Template Library (STL), it is possible for example to create a vector consisting of multiple copies of the same element, using this constructor:

5条回答
  •  伪装坚强ぢ
    2021-01-07 18:01

    var arr = Enumerable.Repeat(x, n).ToArray();
    

    Personally, I'd just use a regular array loop, though:

    var arr = new double[n];
    for(int i = 0 ; i < arr.Length ; i++) arr[i] = x;
    

    More characters, but the array is demonstrably the right size from the outset - no iterative growth List-style and final copy back. Also; simply more direct - and the JIT can do a lot to optimise the for(int i = 0 ; i < arr.Length ; i++) pattern (for arrays).

提交回复
热议问题