0

there is an array in c#

string[] arr = new string[] {"1","A","D","3","5","AF","34","TU","E","OP","4"};

so how can i get elements from middle of this array like below

string[] fromArr = new string[5];
fromArr = {"D","3","5","AF","34"};

Do u know any method or any way to do that?

namco
  • 6,208
  • 20
  • 59
  • 83

4 Answers4

8

The simplest way is to use LINQ2Objects

var fromArr = arr.Skip(2).Take(5).ToArray();

The most performant way would be to use Array.Copy, but that code would be much more cumbersome to write and you need to figure that out yourself, including handling all edge cases when the arrays are not long enough etc.

But if you will use the result just a few times you don't need to copy it back to an array, you can just use the lazy evaluation feature of LINQ2SQL

IEnumerable<string> fromArr = arr.Skip(2).Take(5);

then you can use fromArr in a loop or whatever without even copying the data in the first place.

When I think about it you may have the option to use ArraySegment<string> too instead of copying to new arrays.

But for the readability and simplicity, stick with the LINQ version unless you have a real reason to use another alternative.

Albin Sunnanbo
  • 46,430
  • 8
  • 69
  • 108
4

LINQ has some good approaches to this. In your case

 arr.Skip(2).Take(5).ToArray()

should produce what you need.

A reference is here: http://msdn.microsoft.com/en-us/library/bb386988.aspx

Jeremy McGee
  • 24,842
  • 10
  • 63
  • 95
2

Use LINQ for this

arr.Skip(2).Take(5).ToArray()
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
2

You can use Array.copy to take a slice of an array, for your example:

string[] arr = new string[] {"1","A","D","3","5","AF","34","TU","E","OP","4"};
string[] fromArr = new string[5];
Array.Copy(arr, 2, fromArr, 0, 5);
Óscar López
  • 232,561
  • 37
  • 312
  • 386