开发者

How can I assign a value to multiple array indices at once without looping?

How can I set one value to several elements of the array in C#?

Example:

I have an array initialized as follows:

int[] array=new int[]{2,3,5,3,7,2,9}

and I want to set the va开发者_如何学JAVAlues between the 2-nd and 5-th indices to 8. How it can be done?


Well, if you wanted to get cute, you could create another array that has the value repeated N times, and Copy that to the array:

int[] a = new int[]{2,3,5,3,7,2,9}
int[] replacement = new int[]{8, 8, 8, 8};
Array.Copy(replacement, 0, a, 1, 4);

There's no explicit loop there. But you can bet that there's an implicit loop.

And, if you really wanted to get cute, you could use LINQ to create the replacement array.

Still, this is all academic. As somebody else pointed out, there's no non-looping way to do what you're asking--just highly obfuscated ways that attempt to hide the fact that a loop is taking place.


Just put it in a loop (assuming you want to set the second through fifth elements):

for (int i = 1; i < 5; i++)
{
    array[i] = 8;
}


There are a lot of options in this post: Array slices in C#

There's no magic to set all the options to a value. You're going to have to iterate. But you could always do something like .Take(2) then loop to add 8 for three places, then .Skip(3).Take(rest) or something. Just depends how large the array is.

For large arrays this might help, but it's going to be a lot uglier code if you're only working with Ints or the like. I would just iterate.


Iterate over it and set the appropiate values. There is no shortcut for that.


for (i=0;i<100;i++){
if(i=0)
{array[i]=2}
else{array[i]=(array[i-1]+3)}
}


I thought I'd give an alternate approach which is pretty cool.

int[] array = new int[] { 2,3,5,3,7,2,9 };
var segment = new ArraySegment<int>( array, 2, 5 );
for (int i = segment.Offset; i <= segment.Count; i++)
{
    segment.Array[i] = 8;
}


I choose recursion.

int[] array = new int[] { 2, 3, 5, 3, 7, 2, 9 };
public void caller()
{
    Array8(2, 5);
}

public void Array8 (int start, int end)
{
    if (start <= end)
        Array8(start, --end);
    array[end] = 8;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜