I recently had to initialize an array of boolean to contain only trues.
This are the options that seemed be be usefull.

Extension method:

This post on stack exchange proposes writing an extension method for arrays like this:

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

Which can be called like this:

bool[] arr = new bool[100].Populate(true);

Lambda-expressions

While using an extension method is certainly a good solution, another author proposes using Lambda-Expressions, which seems to be a quicker solution. It might have a longer runtime due to the multiple conversions, though.

bool[] arr = new bool[100].Select(i => true).ToArray();

Enumerable.Repeat()

The easiest solution however seems to be to use the Enumerable.Repeat()-method.

bool[] arr = Enumerable.Repeat<bool>(true, 100).ToArray();

EDIT 04.04.17

A similar case: initializing an bool array with altering values:

bool[] arr = new bool[10]; //all false by default
foreach(int i in Enumerable.Range(0,10).Where(j => j%2 == 0))
    arr[i] = true;
Advertisements