Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# equivalent to Java's Arrays.fill() method [duplicate]

Tags:

java

arrays

c#

I'm using the following statement in Java:

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

Please suggest the C# equivalent.

like image 390
usr021986 Avatar asked Jul 26 '11 09:07

usr021986


2 Answers

I don't know of anything in the framework which does that, but it's easy enough to implement:

// 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 the count instead of the 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;
    }
}
like image 133
Jon Skeet Avatar answered Nov 19 '22 12:11

Jon Skeet


It seems 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 an new larger array with the old values and filling the extra.

For a simple fill try

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

or a sub range

int[] foo = new int[10];
Enumerable.Range(5, 9).Select(i => foo[i] = -1);
like image 2
CCondron Avatar answered Nov 19 '22 14:11

CCondron