User039402
User039402

Reputation: 219

Efficient way to return a part of array (from index)?

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?

Upvotes: 0

Views: 961

Answers (2)

Muhammad Saad
Muhammad Saad

Reputation: 1

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));

Upvotes: 0

Aleks Andreev
Aleks Andreev

Reputation: 7054

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

Upvotes: 1

Related Questions