Home >Backend Development >C++ >How Can I Efficiently Populate a C# Array with a Non-Default Value?

How Can I Efficiently Populate a C# Array with a Non-Default Value?

Barbara Streisand
Barbara StreisandOriginal
2025-01-04 11:27:35671browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn