使用索引返回数组的子集 C#

3

如何在给定fromIndex和toIndex的情况下返回C#数组的子集?

显然,可以使用循环,但是否有其他方法?

这是我要填写的方法签名。

public static FixedSizeList<T> FromExisting(FixedSizeList<T> fixedSizeList, Int32 fromIndex, Int32 toIndex)

FixedSizeList的内部实现是

private T[] _Array;
this._Array = new T[size];

哈哈,是啊,我也刚注意到。泛型让我头疼... - Maxim Gershkovich
3个回答

10
myArray.Skip(fromIndex).Take(toIndex - fromIndex + 1);

编辑: Skip和Take的结果是IEnumerable,并且在你实际使用它之前计数将为零。

如果你尝试

        int[] myArray = {1, 2, 3, 4, 5};
        int[] subset = myArray.Skip(2).Take(2).ToArray();

子集将是{3, 4}


我实际上更喜欢这种方法,但是无法使其工作。无论我传递什么参数给Skip()函数,它都返回0个项目...一定是我做错了什么...嗯嗯 - Maxim Gershkovich
@Maxim 你可以尝试在这个表达式中加入 .ToArray()。 - Bala R
明白了... 没有意识到我在处理 IEnumerable ... 再次感谢朋友 :-) - Maxim Gershkovich
我发现我需要以下内容才能使其工作:using System.Linq; - ariscris

3

3

Array.Copy可以实现您想要的功能,具体请参考这里


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接