Can you count how many times you wrote something like:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var prime = new bool[1000]; | |
for ( int i = 0; i < isPrime.Length; i++ ) | |
{ | |
prime[i] = true; | |
} |
Or if you fancy LINQ (and can sacrifice a bit of performance)?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var prime = Enumerable.Repeat(true, 1000).ToArray(); |
If your answer is infinite or more, then check out the new way available in .NET Core 2.0 and newer:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var data = new bool[1000]; | |
Array.Fill(data, true); |
Array.Fill
brings the best of both worlds – it is more succinct than a for
-loop while being more performant than Enumerable.Repeat
.
As .NET Core is open source and we like to peek under the hood, we can see the Array.Fill
method is basically just a shorthand for plain for
loop:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static void Fill<T>(T[] array, T value) | |
{ | |
if (array == null) | |
{ | |
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); | |
} | |
for (int i = 0; i < array.Length; i++) | |
{ | |
array[i] = value; | |
} | |
} |
It is also worth mentioning that Array.Fill
has another overload which lets us specify which range of indices should be filled:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static void Fill<T> (T[] array, T value, int startIndex, int count); |
Thx and I translated your blog [dotnet core 用值初始化整个数组](https://lindexi.oschina.io/lindexi/post/dotnet-core-%E7%94%A8%E5%80%BC%E5%88%9D%E5%A7%8B%E5%8C%96%E6%95%B4%E4%B8%AA%E6%95%B0%E7%BB%84.html )