I'm using the following statement in Java:
Arrays.fill(mynewArray, oldArray.Length, size, -1);
Please suggest the C# equivalent.
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;
}
}
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);
Try like this
Array.Copy(source, target, 5);
For more information here
精彩评论