73

I would like to select a range of items in an array of items. For example I have an array of 1000 items, and i would like to "extract" items 100 to 200 and put them in another array.

Can you help me how this can be done?

2
  • 2
    Make sure to accept an answer if it helps you. Commented Jun 28, 2010 at 5:27
  • Does this answer your question? Array slices in C# Commented Mar 8, 2023 at 17:08

1 Answer 1

139

In C# 8, range operators allow:

var dest = source[100..200];

(and a range of other options for open-ended, counted from the end, etc)

Before that, LINQ allows:

var dest = source.Skip(100).Take(100).ToArray();

or manually:

var dest = new MyType[100];
Array.Copy(source, 100, dest, 0, 100);
       // source,source-index,dest,dest-index,count
Sign up to request clarification or add additional context in comments.

3 Comments

It also has to be a core app. dot net 4.8 doesn't like it even if it's C#9, missing System.Range and System.Index.
@MarcGravell It seems odd to me that array[1..10] creates a new array with a copy of the data (and appears to be syntactic shorthand for RuntimeHelpers.GetSubArray()); whereas span[1..10] gets a slice on that span (and is shorthand for .Slice()). I imagine this has come about due to legacy reasons, but to me it feels like it fails the "test of least astonishment".
I find C#'s syntax of excluding the last item in the range unintuitive using the source[100..200] syntax. Specifically, the OP asked items 100 to 200 to be extracted, which should include item 200, i.e. it is 101 items in total. @MarcGravell's solution excludes item 200.

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.