我有一个包含10个元素的数组X。我想创建一个新数组,包含X中从索引3开始并在索引7结束的所有元素。当然,我可以很容易地写一个循环,将它为我,但我想保持我的代码尽可能干净。c#中有一个方法可以帮我做这个吗?

类似(伪代码):

Array NewArray = oldArray.createNewArrayFromRange(int BeginIndex , int EndIndex)

数组中。拷贝不符合我的需要。我需要在新数组中的项目是克隆。数组中。copy只是一个c风格的memcpy等效,这不是我要找的。


当前回答

在c# 8中,他们引入了一个新的范围和索引类型,可以这样使用:

int[] a = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Index i1 = 3;  // number 3 from beginning
Index i2 = ^4; // number 4 from end
var slice = a[i1..i2]; // { 3, 4, 5 }

引用:

https://learn.microsoft.com/en-us/dotnet/core/whats-new/dotnet-core-3-0#ranges-and-indices https://devblogs.microsoft.com/dotnet/building-c-8-0/

其他回答

array1 = [5,6,7,8];

int[] array2 = new int[2];

Array.ConstrainedCopy(array1, 1, array2, 0, 2);

array2 = [6,7];

数组中。ConstrainedCopy有五个(5)参数:

源数组 源数组的起始索引(sourceIndex) 目标数组(destinationArray) 目标数组起始索引(destinationIndex) 要复制的元素数量(长度)

那么使用数组呢?ConstrainedCopy:

int[] ArrayOne = new int[8] {1,2,3,4,5,6,7,8};
int[] ArrayTwo = new int[5];
Array.ConstrainedCopy(ArrayOne, 3, ArrayTwo, 0, 7-3);

以下是我的原帖。这是行不通的

你可以使用数组。CopyTo:

int[] ArrayOne = new int[8] {1,2,3,4,5,6,7,8};
int[] ArrayTwo = new int[5];
ArrayOne.CopyTo(ArrayTwo,3); //starts copy at index=3 until it reaches end of
                             //either array

使用扩展方法:

public static T[] Slice<T>(this T[] source, int start, int end)
    {
        // Handles negative ends.
        if (end < 0)
        {
            end = source.Length + end;
        }
        int len = end - start;

        // Return new array.
        T[] res = new T[len];
        for (int i = 0; i < len; i++)
        {
            res[i] = source[i + start];
        }
        return res;
    }

你可以使用它

var NewArray = OldArray.Slice(3,7);

这很容易做到;

    object[] foo = new object[10];
    object[] bar = new object[7];   
    Array.Copy(foo, 3, bar, 0, 7);  

它不符合你的克隆要求,但它似乎比许多答案要简单:

Array NewArray = new ArraySegment(oldArray,BeginIndex , int Count).ToArray();