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

后端 未结 5 1732

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 17:45
    double[] theSameValues = Enumerable.Repeat(2.0, 10).ToArray();
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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<T>-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).

    0 讨论(0)
  • 2021-01-07 18:05

    the for each (or better the classic for) is always much faster than using Linq. You should use the Linq expression only if it makes the code more readable

    0 讨论(0)
  • 2021-01-07 18:08

    In VB.NET

    Imports System.Linq

    Dim n As Integer = 10
    
    Dim colorArray = New Color(n - 1) {}.[Select](Function(item) Color.White).ToArray()
    
    0 讨论(0)
提交回复
热议问题