Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Array initialization - with non-default value

Tags:

c#

.net

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[] GetPageNumbersToLink(IPagedResult result)
{
   if (result.TotalPages <= 9)
      return new bool[result.TotalPages + 1].Select(b => true).ToArray();

   ...
like image 293
Rob Avatar asked Sep 25 '08 23:09

Rob


2 Answers

If by 'slickest' you mean fastest, I'm afraid that Enumerable.Repeat may be 20x slower than a for loop. See http://dotnetperls.com/initialize-array:

Initialize with for loop:             85 ms  [much faster]
Initialize with Enumerable.Repeat:  1645 ms 

So use Dotnetguy's SetAllValues() method.

like image 119
Nigel Touch Avatar answered Nov 20 '22 14:11

Nigel Touch


use Enumerable.Repeat

Enumerable.Repeat(true, result.TotalPages + 1).ToArray()
like image 38
Mark Cidade Avatar answered Nov 20 '22 15:11

Mark Cidade