0

So lets say we have an array of doubles like this one that is later used for other stuff.

double[] myArray = new double[25];

How would I go about replacing all the values in that array with a set value?

anthony corrado
  • 91
  • 1
  • 1
  • 5

2 Answers2

6

There are flashier ways, but

for (int i = 0; i < myArray.Length; ++i){
    myArray[i] = foo; /*the new value*/
}

is clear and simple.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
6

The "flashy" way (simply create a new array):

var array = Enumerable.Repeat(value, count).ToArray();

Or

Array.ConvertAll(array, e => value);
Manfred Radlwimmer
  • 13,257
  • 13
  • 53
  • 62
  • Showoff ;-) Have an upvote. – Bathsheba Dec 02 '16 at 09:20
  • I think instead of `count` better to write myArray.Length? – Ali Bahrami Dec 02 '16 at 09:21
  • 1
    `Repeat` is less efficient than the for-loop approach and `ConvertAll` is made for a different purpose(convert the type), so a bit misleading. It's also using the for-loop[[source](https://referencesource.microsoft.com/#mscorlib/system/array.cs,f4af030bcf8c8991,references)]. – Tim Schmelter Dec 02 '16 at 09:24
  • Flashy ways will create new instance of array instead of updating existed one – Fabio Dec 02 '16 at 09:25
  • @TimSchmelter Totally aware of that ^^. I just wanted to complete Bathsheba's answer since he mentioned *flashy* ways. There are of course countless other ways of abusing built in methods for this purpose. – Manfred Radlwimmer Dec 02 '16 at 09:30