Kevin
Kevin

Reputation: 9389

Pass reference to element in C# Array

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#?

Upvotes: 6

Views: 4385

Answers (5)

joshperry
joshperry

Reputation: 42317

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);

Upvotes: 5

joshperry
joshperry

Reputation: 42317

List<string> parts = new List<string>(s.Split(" "));
parts.RemoveRange(0, x - 2);

Assuming that List<string>(string[]) is optimized to use the existing array as a backing store instead of doing a copy operation this could be faster than doing an array copy.

Upvotes: 0

toolkit
toolkit

Reputation: 50297

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.

Upvotes: 2

Frank Krueger
Frank Krueger

Reputation: 71063

Array.Copy Method

I guess something like:

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

(sans the off by 1 bug that I'm sure is in there.)

Upvotes: -1

Ryan Farley
Ryan Farley

Reputation: 11431

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

Array.Copy (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.

Upvotes: -1

Related Questions