C # is equivalent to Java's Arrays.fill () method

I use the following statement in Java:

Arrays.fill(mynewArray, oldArray.Length, size, -1); 

Please suggest the equivalent of C #.

+6
source share
3 answers

I do not know anything in the structure that does this, but it is quite simple to implement it:

 // Note: start is inclusive, end is exclusive (as is conventional // in computer science) public static void Fill<T>(T[] array, int start, int end, T value) { if (array == null) { throw new ArgumentNullException("array"); } if (start < 0 || start >= end) { throw new ArgumentOutOfRangeException("fromIndex"); } if (end >= array.Length) { throw new ArgumentOutOfRangeException("toIndex"); } for (int i = start; i < end; i++) { array[i] = value; } } 

Or, if you want to specify a counter instead of a start / end:

 public static void Fill<T>(T[] array, int start, int count, T value) { if (array == null) { throw new ArgumentNullException("array"); } if (count < 0) { throw new ArgumentOutOfRangeException("count"); } if (start + count >= array.Length) { throw new ArgumentOutOfRangeException("count"); } for (var i = start; i < start + count; i++) { array[i] = value; } } 
+9
source

try it

 Array.Copy(source, target, 5); 

For more information here

+1
source

It looks like you would like to do something more like this

 int[] bar = new int[] { 1, 2, 3, 4, 5 }; int newSize = 10; int[] foo = Enumerable.Range(0, newSize).Select(i => i < bar.Length ? bar[i] : -1).ToArray(); 

Creating a new larger array with old values ​​and filling in additional ones.

For a simple attempt to fill

 int[] foo = Enumerable.Range(0, 10).Select(i => -1).ToArray(); 

or subband

 int[] foo = new int[10]; Enumerable.Range(5, 9).Select(i => foo[i] = -1); 
0
source

Source: https://habr.com/ru/post/893577/


All Articles