0

There is an array of ints, where I am interested in those that start from index 10. Therefore, I am writing a method that would return a new array, which consists of 11th and further elements. I tried the Array.Copy but it does not have the option I need. What would be the best way for this?

1
  • Array is IEnumerable so use Skip() and Take(). Commented Sep 24, 2017 at 11:36

2 Answers 2

1

You can use an ArraySegment

var source = new int[20];
var segment = new ArraySegment<int>(source, 10, source.Length - 10);

This is lightweight struct and it implements an IEnumerable<T> interface so you can use linq on it.

EDIT: In case you really need an array as return type you can create a new array with linq:

source.Skip(9).ToArray(); // skip from 0 to 9 and use a rest of source array

However this will allocate additional memory for array copy

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

Comments

0
public static T[] SubArray<T>(this T[] data, int index, int length)
{
    T[] result = new T[length];
    Array.Copy(data, index, result, 0, length);
    return result;
}    

int startIndex=10;
    int[] data = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
    int[] sub = data.SubArray(startIndex, (data.Length-startIndex)-1));

2 Comments

There is no such method: SubArray.
thanks Dmitry, code of specified method have up-dated in posted solution.

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.