1

i am trying to copy parts of an array to a new array and searched for a solution, but al those solutions were allot of coding or were not exactly what i was looking for. it might be that i searched wrong on google, but sorry if the answer to this is to easy to find, i couldnt find it.

i have array A

string[] A = {"A", "B", "C", "D", "E", "F"};

i tried to copy parts of it to array B using

string[] B = new string[2]; Array.Copy(A, 0, B, 0, 2)

but this just gives a fixed part of array A back so array B consists of "A" and "B".

is there also a way to give array B values 0, 1, 4, 5. so it gives me "A" "B" "E" and "F"

also sorry for bad english it is not my native language, and i tried to search on google for :

allot of the results of my first searches got me to pages about how to get an 2D array but that is not what i need. "How to copy 2 parts of an array to a new array" what lead me to array.copy tag after that i tried to look up "array.copy manual" but that only lead me to beleave it cant be done with array.copy so does anyone know how to do this in a compact code?

again. sorry if this answer is to obvious.

B. Dionys
  • 916
  • 7
  • 34
  • have a look: http://stackoverflow.com/questions/733243/how-to-copy-part-of-an-array-to-another-array-in-c – M.Hassan Nov 05 '16 at 11:05

3 Answers3

3

is there also a way to give array B values 0, 1, 4, 5. so it gives me "A" "B" "E" and "F"

No, because B is an array of strings. However, you can start with a separate array of indexes, and copy from A based on them:

int[] indexes = new[] {0, 1, 4, 5};
string[] B = indexes.Select(i => A[i]).ToArray();
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 1
    nice solution. only could be wrong on bound checking. `int[] = new[] { 0,1, 15 };` might be: `string[] B = indexes.Where(i => i < A.Length).Select(i => A[i]).ToArray();` – Jeroen van Langen Nov 05 '16 at 11:07
  • @JeroenvanLangen OP's the one constructing the array of indexes, so observing the proper bounds is on him. – Sergey Kalinichenko Nov 05 '16 at 11:08
  • yours is more profesional it works i found a solution myself just now, but ill use yours and put mine in comment under it for refference purposes thank you. – B. Dionys Nov 05 '16 at 11:16
1

One way could be:

var indices = new[] { 0, 1, 4, 5 };
var copy = A.Where((s, i) => indices.Contains(i)).ToArray();
Jeroen van Langen
  • 21,446
  • 3
  • 42
  • 57
0

uhm i just went booging arround with my code and this works i guess:

string[] A = {"A", "B", "C", "D", "E", "F"}; string[] B = new string[4]; Array.Copy(A, 0, B, 0, 2) Array.Copy(A, 4, B, 2, 2)

it gives array B values A B E and F

B. Dionys
  • 916
  • 7
  • 34