B. Dionys B. Dionys - 1 month ago 8
C# Question

How to copy parts of an array to a new array. C#

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.

Answer

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