67

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,923
  • 18
  • 54
  • 73

1 Answers1

128

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
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • 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
  • 2
    @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
  • 5
    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