TechnoCF TechnoCF - 1 month ago 8
C# Question

How to get part of a string[] array in C#

How, using C#, can I create a new string[] from another string[] containing a subsection of the old string[] array?

For example, if I had:

string[] a = { "cat", "dog", "hamster", "parrot" }


And I wanted to get everything after the first element I should get:

string[] b = { "dog", "hamster", "parrot" }


How, if this is even possible without a for loop, do I achieve this?

Answer

You can use some extensions methods to solve it, that is the case for Skip(int) under the System.Linq namespace, for sample:

string[] b = a.Skip(1).ToArray();

And it will skip 1 element and convert the result into a new array. Remember to add the namespace:

using System.Linq;

As the MSDN documentation said:

Bypasses a specified number of elements in a sequence and then returns the remaining elements.