Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass reference to element in C# Array

Tags:

arrays

c#

I build up an array of strings with

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

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

parts[x-2]

Other than the obvious brute force approach (make a new array and insert strings), is there a more elegant way to do this in C#?

like image 441
Kevin Avatar asked Aug 27 '08 19:08

Kevin


2 Answers

I remembered answering this question and just learned about a new object that may provide a high performance method of doing what you want.

Take a look at ArraySegment<T>. It will let you do something like.

string[] parts = myString.spilt(" ");
int idx = parts.Length - 2;
var stringView = new ArraySegment<string>(parts, idx, parts.Length - idx);
like image 122
joshperry Avatar answered Oct 21 '22 07:10

joshperry


How about Array.Copy?

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

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

Copies a range of elements from an Array starting at the specified source index and pastes them to another Array starting at the specified destination index. The length and the indexes are specified as 32-bit integers.

like image 42
toolkit Avatar answered Oct 21 '22 06:10

toolkit