56

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?

mouthpiec
  • 3,613
  • 17
  • 51
  • 72

1 Answers1

106

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
Marc Gravell
  • 976,458
  • 251
  • 2,474
  • 2,830
  • 4
    @julianbechtold it is also 9 years out of date; C# 8 adds range and index-based operations as first-class citizens; I'll update the example, but use your python example or `myArray[100:200]`, in C# 8 that is `myArray[100..200]` – Marc Gravell May 08 '19 at 13:49
  • 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. – robsn Nov 13 '20 at 14:18
  • 1
    @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". – redcalx Dec 30 '20 at 22:04
  • 2
    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. – Froggy Sep 15 '21 at 11:10