简体   繁体   中英

Initialize runtime value-type array with specific value?

Is there a way I can initialize the following runtime array to all true s without looping over it using a foreach?

Here is the declaration:

bool[] foo = new bool[someVariable.Count];

Thanks!

bool[] foo = Enumerable.Repeat(true, someVariable.Count)
                       .ToArray();
bool[] bools = (new bool[someVariable.Count]).Select(x => !x).ToArray();

Sort of kidding. Kind of. Almost.

Is any kind of explicit looping forbidden, or are you only concerned about avoiding foreach ?

bool[] foo = new bool[someVariable.Count];
for (int i = 0; i < foo.Length; i++) foo[i] = true;
bool[] foo = new bool[]{true,true,true,...};

This is the only way in C# known to me to initialize an Array to a certain value other than the default value which does not involve creating other temporary objects. It would be great if class Array had some method like Fill() or Set().

Correcty me if Iam wrong.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM