English 中文(简体)
我怎么能够一劳永逸地给多种阵列指数分配价值?
原标题:How can I assign a value to multiple array indices at once without looping?
  • 时间:2010-12-10 20:59:04
  •  标签:
  • c#
  • arrays

我如何对C#中阵列的若干要素设定一个价值?

Example:

我的阵列如下:

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

and I want to set the values between the 2-nd and 5-th indices to 8. How it can be done?

最佳回答

如果你想要打断,你就可以制造另一个具有重复N时间价值的阵列和<代码>。 表格:

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);

这里没有explicit。 但你可以认为,存在暗含的漏洞。

而且,如果你真的想要切割,你可以使用LINQ制造<代码>replacement/code>阵列。

尽管如此,这是所有学术性的。 正如其他人指出的,没有不妥协的方式来做你重新要求高度模糊的方法,试图掩盖正在发生的 lo。

问题回答

只是把它放在一旁(假设你想要确定第二至第五点要素):

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

这个职位有许多选择:。 C#中的覆盖物

没有任何魔力把所有选择都设定为价值。 你们会ate。 但是,你总是能够做像Take(2)那样的事情,然后在三个地方增加8个,然后是Skip(3)。 采取(逮捕)或采取某种行动。 仅仅取决于阵列的规模。

对于大型阵列来说,这可能有助于,但如果你只与Ints或类似公司重新合作,它就会成为一种很大的ug。 我只想.。

由此而来,并设定了代谢价值。 没有任何捷径。

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;
}

我选择再行。

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;
}




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签