Get values from Arraysegment

Asked

Viewed 61 times

3

By creating a ArraySegment, would like to get the new array created, but when using:

meuSegmento.Array;

the array original is returned and not the created segment.

string[] meuArray = {"stack", "overflow","em", "português"};
var meuSegmento = new ArraySegment<string>(meuArray, 2, (meuArray.Length - 1));
string[] arraySegmentado = meuSegmento.Segmento; //Quero o seguimento criado: { "em", "português" }
  • meSegmento.Array was to be right, basically as shown here http://www.dotnetperls.com/arraysegment

  • 1

    First that the second element should be new ArraySegment<string>(meuArray, 2, (meuArray.Length - 3));, since the second parameter is relative to how many elements from index 2 you want to pick up. Second to traverse Arraysegment only using a for as follows: for(var i = segmento.Offset; i < segmento.Count+ segmento.Offset; i++). So the real usefulness of Arraysegment would be more for LINQ queries.

  • @Thiagofriedman, actually no, what the meuSegmento.Array returns, according to its reference link, is, precisely, the original vector.

  • @Felipeavelar did not understand, because his reference to create Arraysegment is the original vector too, ie meuArray

1 answer

2


Do so:

string[] meuArray = {"stack", "overflow","em", "português"};
var meuSegmento = new ArraySegment<string>(meuArray, 2, (meuArray.Length - 2));
string[] arraySegmentado = meuSegmento.ToArray();

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

But then you’ll do something that probably was trying to avoid. There is no free lunch. As I said there, maybe the need requires a completely different data structure.

You may have to live with the low performance. Not every problem can be solved as we wish. There’s probably a proper structure, you just need to see if it pays off to implement it if it’s not ready for language.

Perhaps the problem is another and a full replanning is needed.

  • Toarray() is only available in the version of . Net Framework 4.5 onwards, or can it also be used in version 4? I tried here, but was unsuccessful!

  • Been around since 3.5.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.