Home >Backend Development >C++ >How Can I Efficiently Populate a C# Array with a Non-Default Value?
How to Populate a C# Array with a Non-Default Value
C# arrays of value types are initialized with default values, such as false for bool or 0 for int. While Java offers the Arrays.fill() method, is there a way to auto-populate a C# array with a custom value during creation or later?
Many developers have attempted to resolve this issue by manually iterating through the array and assigning each element the desired value. However, this approach can be inefficient.
Customizing Array Initialization Using Enumerable.Repeat()
Fortunately, there is a built-in solution in C# using the Enumerable.Repeat() method:
bool[] abValues = Enumerable.Repeat(true, 1000000).ToArray();
The Enumerable.Repeat() method creates a sequence of a specified value repeated the given number of times. By converting this sequence to an array using ToArray(), you can auto-populate an array with a custom value.
This method is efficient and eliminates the need for manual iteration. It operates on a higher level of abstraction, dealing with sequences rather than modifying individual array elements.
Therefore, the answer to the question is yes: C# provides a built-in way to auto-populate arrays with a non-default value usingEnumerable.Repeat().
The above is the detailed content of How Can I Efficiently Populate a C# Array with a Non-Default Value?. For more information, please follow other related articles on the PHP Chinese website!