Dokážete spočítat, kolikrát jste napsali něco jako:
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; | |
} |
Nebo, pokud milujete LINQ, (a nevadí vám mírně horší výkonnost)?
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(); |
Pokud jste odpověděli “nekonečněkrát” či více, vyzkoušejte nový způsob k dispozici v .NET Core 2.0 a novějších:
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
přináší to nejlepší z obou světů – je stručnější než ručně psaný for
cyklus zatímco je rychlejší než Enumerable.Repeat
.
A protože je .NET Core open source můžeme se podívat přímo pod kapotu na implementaci metody Array.Fill
a všimnout si, že jde vlastně pouze o zkratku pro celý for
cyklus:
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; | |
} | |
} |
Stojí také za zmínku, že Array.Fill
má další overload který dovoluje specifikovat rozsah indexů, které mají být vyplněny:
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); |