C # array initialization - with non-standard value

What is the smoothest way to initialize a dynamic size array in C # that you know about?

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(); ... 
+31
c #
Sep 25 '08 at 23:22
source share
6 answers

use Enumerable.Repeat

 Enumerable.Repeat(true, result.TotalPages + 1).ToArray() 
+35
Sep 26 '08 at 0:56
source share

If you consider "slickest" to be the fastest, I am afraid that Enumerable.Repeat might be 20 times slower than the loop for . See http://dotnetperls.com/initialize-array :

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

Therefore, use the Dotnetguy SetAllValues ​​() method.

+70
Jun 26 '09 at 20:49
source share

EDIT: as the commentator noted, my initial implementation did not work. This version works, but rather nonsmooth, based on the for loop.

If you want to create an extension method, you can try this

 public static T[] SetAllValues<T>(this T[] array, T value) where T : struct { for (int i = 0; i < array.Length; i++) array[i] = value; return array; } 

and then call it like this:

 bool[] tenTrueBoolsInAnArray = new bool[10].SetAllValues(true); 

Alternatively, if you are happy that the class is hanging around, you can try something like this

 public static class ArrayOf<T> { public static T[] Create(int size, T initialValue) { T[] array = (T[])Array.CreateInstance(typeof(T), size); for (int i = 0; i < array.Length; i++) array[i] = initialValue; return array; } } 

which you can call as

 bool[] tenTrueBoolsInAnArray = ArrayOf<bool>.Create(10, true); 

Not sure what I prefer, although I use lurv extension methods many and many in general.

+13
Sep 26 '08 at 0:46
source share

I would suggest this:

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

This way you select only one array. This is essentially a more concise way of expressing:

 var array = new bool[count]; for(var i = 0; i < count; i++) { array[i] = true; } return array; 
+5
Sep 26 '08 at 0:34
source share

Many times you would like to initialize different cells with different values:

 public static void Init<T>(this T[] arr, Func<int, T> factory) { for (int i = 0; i < arr.Length; i++) { arr[i] = factory(i); } } 

Or in factory color:

 public static T[] GenerateInitializedArray<T>(int size, Func<int, T> factory) { var arr = new T[size]; for (int i = 0; i < arr.Length; i++) { arr[i] = factory(i); } return arr; } 
+1
Oct 09 '14 at 11:37
source share

Unconfirmed, but can you just do it?

 return result.Select(p => true).ToArray(); 

Skip the "new part bool []"?

0
Sep 25 '08 at 23:36
source share



All Articles