Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fill an array in C# [duplicate]

Tags:

In Java there are about 18 a static "fill" methods in the class Arrays that serve to assign one value to each element in an array. I'm looking for an equivalent in C# to achieve the same thing but I'm not finding anything with the same compactness:

1) ForEach as I understand passes elements in the array by value so I can't change them

2) Repeat from Enumerable creates a new array, it seems to be overhead to create a new array and then copy each element from the array

3) a for-loop isn't pretty, which I guess is why the Java folks introduced this compact notation to begin with

4) The Clear method from the Array class can set everything to zero, but then how do I convert zero to the non-zero value I want?

To demonstrate Java's syntax consider this code that prints three times the number 7:

int[] iii = {1, 2, 3}; Arrays.fill(iii, 7); for (int i : iii) {     System.out.println(i); } 
like image 695
Mishax Avatar asked Feb 17 '13 08:02

Mishax


People also ask

How do you fill in an array?

Using the fill() method The fill() method, fills the elements of an array with a static value from the specified start position to the specified end position. If no start or end positions are specified, the whole array is filled. One thing to keep in mind is that this method modifies the original/given array.


2 Answers

int[] arr = Enumerable.Repeat(42, 10000).ToArray(); 

I believe that this does the job :)

like image 59
Alex Shtof Avatar answered Oct 02 '22 02:10

Alex Shtof


Write yourself an extension method

public static class ArrayExtensions {     public static void Fill<T>(this T[] originalArray, T with) {         for(int i = 0; i < originalArray.Length; i++){             originalArray[i] = with;         }     }   } 

and use it like

int foo[] = new int[]{0,0,0,0,0}; foo.Fill(13); 

will fill all the elements with 13

like image 29
bradgonesurfing Avatar answered Oct 02 '22 02:10

bradgonesurfing