开发者

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

开发者 https://www.devze.com 2023-03-23 11:49 出处:网络
This question already has answers here: How to populate/instantiate a C# array with a single value? 开发者_开发技巧
This question already has answers here: How to populate/instantiate a C# array with a single value? 开发者_开发技巧 (26 answers) Closed 8 years ago.

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

0

精彩评论

暂无评论...
验证码 换一张
取 消