开发者

Initialize runtime value-type array with specific value?

开发者 https://www.devze.com 2023-01-19 15:33 出处:网络
Is there a way I can initialize the following runtime array to all trues without looping over it using a foreach?

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

Here is the declaration:

bool[] foo = new bool[someVar开发者_StackOverflowiable.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.

0

精彩评论

暂无评论...
验证码 换一张
取 消