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[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.
精彩评论