0

I'd like to pull a section of an array out for manipulation.

e.g. From an array that contains 50 items, i want to return items 12 to 22 in a new array

Im currently using LINQ which I am assuming is slow:

return fullArray.Skip(12).Take(22).ToArray();

Is there a quicker way?

3
  • Why are you assuming it's slow? Commented Sep 13, 2013 at 10:42
  • 1
    @Vijay He's assuming it, but I've tested it (for exactly this Take/Skip scenario) and it is orders of magnitude slower. I agree that he should have profiled first though :) Commented Sep 13, 2013 at 10:47
  • That's what I was kinda getting at, I know he said "assumed", but people do that all the time with linq and a lot of the time there is little to no difference in performance, at least nothing easily measurable! I'll use this method instead of take/skip for my paging in the future :) Commented Sep 13, 2013 at 11:37

2 Answers 2

6

The Array.Copy method is massively quicker than Linq (I've tested it before and it was 2 or 3 orders of magnitude quicker!)

var sourceArray = object[50];
var newArray = object[10];
// Copy 10 elements, starting at index 12, to newArray (starting at index 0)
Array.Copy(sourceArray, 12, newArray, 0, 10);
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry, Im a bit of a n00b with arrays - thanks for the quick answer!
0

You can use Array.Copy Method (Array, Int32, Array, Int32, Int32) method;

Copies a range of elements from an Array starting at the specified source index and pastes them to another Array starting at the specified destination index. The length and the indexes are specified as 32-bit integers.

For example;

int[] array1 = new int[50];
int[] array2 = new int[10];
Array.Copy(array1, 12, array2, array2.GetLowerBound(0), 10);

1 Comment

The reign of the downvoters is here it seems :) Not the first time an answer has been downvoted without reason.

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.