C# Array initialization - with non-default value

前端 未结 6 1842
温柔的废话
温柔的废话 2020-12-08 20:03

What is the slickest way to initialize an array of dynamic size in C# that you know of?

This is the best I could come up with

private bool[] GetPageN         


        
6条回答
  •  生来不讨喜
    2020-12-08 20:25

    I would actually suggest this:

    return Enumerable.Range(0, count).Select(x => true).ToArray();
    

    This way you only allocate one array. This is essentially a more concise way to express:

    var array = new bool[count];
    
    for(var i = 0; i < count; i++) {
       array[i] = true;
    }
    
    return array;
    

提交回复
热议问题