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

后端 未结 5 1839

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条回答
  •  梦毁少年i
    2021-01-07 17:52

    What about this?

    double[] v = Enumerable.Repeat(x, n).ToArray();
    

    EDIT: I just did a small benchmark; to create 1000 arrays of 100000 elements each, using a loop is about 3 times faster that Enumerable.Repeat.

    Repeat 
    00:00:18.6875488 
    
    Loop 
    00:00:06.1628806 
    

    So if performance is critical, you should prefer the loop.

提交回复
热议问题