Pass a reference to an element in a C # array

I create an array of strings with

string[] parts = string.spilt(" "); 

And to get an array with X parts in it, I would like to get a copy of the array of strings starting from the element

 parts[x-2] 

Besides the obvious brute force approach (create a new array and insert lines), is there a more elegant way to do this in C #?

+6
arrays c #
source share
5 answers

What about Array.Copy?

http://msdn.microsoft.com/en-us/library/aa310864(VS.71).aspx

Array.Copy Method (Array, Int32, Array, Int32, Int32)

Copies a series of elements from an array, starting at the specified source index, and pastes them into another array, starting at the specified target index. Length and indices are specified as 32-bit integers.

+2
source share

I remember answering this question and just found out about a new object that can provide a high-performance method for doing what you want.

Take a look at ArraySegment<T> . This will allow you to do something like.

 string[] parts = myString.spilt(" "); int idx = parts.Length - 2; var stringView = new ArraySegment<string>(parts, idx, parts.Length - idx); 
+6
source share
 List<string> parts = new List<string>(s.Split(" ")); parts.RemoveRange(0, x - 2); 

Assuming List<string>(string[]) optimized to use an existing array as a backup storage instead of performing a copy operation, this may be faster than executing an array copy.

0
source share

Use Array.Copy . It has an overload that does what you need:

Array.Copy (array, Int32, array, Int32, Int32)
Copies a number of elements from an array, starting from the specified source index and pasting them into another array starting from the specified destination index.

-one
source share

Array.Copy Method

I think something like:

 string[] less = new string[parts.Length - (x - 2)]; Array.Copy(parts, x - 2, less, 0, less.Length); 

(1 error is disabled, which I am sure is there.)

-one
source share

All Articles