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
Untested, but could you just do this?
return result.Select(p => true).ToArray();
Skipping the "new bool[]" part?
EDIT: as a commenter pointed out, my original implementation didn't work. This version works but is rather un-slick being based around a for loop.
If you're willing to create an extension method, you could 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 invoke it like this
bool[] tenTrueBoolsInAnArray = new bool[10].SetAllValues(true);
As an alternative, if you're happy with having a class hanging around, you could 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 invoke like
bool[] tenTrueBoolsInAnArray = ArrayOf<bool>.Create(10, true);
Not sure which I prefer, although I do lurv extension methods lots and lots in general.
use Enumerable.Repeat
Enumerable.Repeat(true, result.TotalPages + 1).ToArray()
Many times you'd want 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 the factory flavor:
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;
}
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;
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.