开发者

Return a subset of Array using index C#

开发者 https://www.devze.com 2023-02-15 08:59 出处:网络
What is the best way to return a subset of a C# array given a fromIndex and toIndex?开发者_开发知识库

What is the best way to return a subset of a C# array given a fromIndex and toIndex?开发者_开发知识库

Obviously I can use a loop but are there other approaches?

This is the method signature I am looking to fill.

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

FixedSizeList internal implementation is

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


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

EDIT: The result of Skip and Take are IEnumerable and the count will be zero until you actually use it.

if you try

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

subset will be {3, 4}


List Already has a CopyTo Method which should do what you want.

http://msdn.microsoft.com/en-us/library/3eb2b9x8.aspx

This is the Signature of the method:

public void CopyTo( int index, T[] array, int arrayIndex,   int count )


Array.Copy will do what you want.

0

精彩评论

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