3

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];
1
  • lol, yeah just noticed that myself. Generics hurts my brain... Commented Mar 7, 2011 at 3:04

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

4 Comments

I actually liked this approach more then all of them but am failing to get it working. Skip() no matter what I pass in returns 0 items... Must be doing something wrong... hmmmm
@Maxim you could try adding .ToArray() to the expression.
Got ya... Didn't catch on that I was dealing with IEnumerable... Thanks again mate :-)
I found that I need the following to make this work: using System.Linq;
3

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 )

Comments

3

Array.Copy will do what you want.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.