If I have an array with 12 elements and I want a new array with that drops the first and 12th elements. For example, if my array looks like this:
__ __ __ _
C# 8 has a Range
and Index
type
char[] a = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l' };
Index i1 = 1; // number 1 from beginning
Index i2 = ^1; // number 1 from end
var slice = a[i1..i2]; // { 'b','c','d','e','f','g','h','i','j' }
You can do this with Array.Copy or LINQ.
var letters = string[] { "a", "b", "c", "d", "e", "f", "g", "h", "i" };
int length = letters.Length - 2;
var items = new string[length];
Array.Copy(letters, 1, items, 0, length);
// or
var items = letters.Skip(1).Take(length).ToArray();
You can use ArraySegment<T>
structure like below:
var arr = new[] { 1, 2, 3, 4, 5 };
var offset = 1;
var count = 2;
var subset = new ArraySegment<int>(arr, offset, count)
.ToArray(); // output: { 2, 3 }
Check here for an extension method that makes use of it even easier.
LINQ is your friend. :)
var newArray = oldArray.Skip(1).Take(oldArray.Length - 2).ToArray();
Somewhat less efficient than manually creating the array and iterating over it of course, but far simple...
The slightly lengithier method that uses Array.Copy is the following.
var newArray = new int[oldArray.Count - 2];
Array.Copy(oldArray, 1, newArray, 0, newArray.Length);
Array.Copy() will do that for you, but you still have to create your new array with its correct size.
string[] s = initialize the array...
var subset = s.Skip(1).Take(s.Length - 2).ToArray();