Anurag
Anurag

Reputation: 572

Conversion of string array into another string array on the basis of a parameter

I have another question.

How to convert a string array to another string array on the basis of a parameter?

string[] x={ "A", "B", "C", "D", "E", "F", "G" };
string[] y=new string[number];

for(int I=0;i<number;i++)
{
y=x[i];
}

The above implementation shows error.

If the parameter number is 3, then array y should have A,B,C,D.

Basically on the basis of a parameter, I want to generate another array from the parent array

I know this question is not too high-tech but I am not able to get around it.

Help will be greatly appreciated.

Regards

Anurag

Upvotes: 1

Views: 52

Answers (4)

Soner G&#246;n&#252;l
Soner G&#246;n&#252;l

Reputation: 98750

Array.Copy has an overload called Array.Copy Method (Array, Array, Int32)

Copies a range of elements from an Array starting at the first element and pastes them into another Array starting at the first element.

Array.Copy(x, y, number + 1);

For a full example;

string[] x = { "A", "B", "C", "D", "E", "F", "G" };
string[] y = new string[4];
Array.Copy(x, y, 4);
foreach (var item in y)
{
    Console.WriteLine(item);
}

Output will be;

A
B
C
D

Here a demonstration.

Upvotes: 4

TomT
TomT

Reputation: 971

First you need a bigger array if number=3 should give you A,B,C,D

string[] x={ "A", "B", "C", "D", "E", "F", "G" };
string[] y=new string[number+1];

And use Array.Copy to copy the elements

Array.Copy(x, y, number+1);

Upvotes: 0

CodingIntrigue
CodingIntrigue

Reputation: 78545

It shows an error because you have declared int I, but tried to access i and also, you need to access y using an indexer:

string[] x={ "A", "B", "C", "D", "E", "F", "G" };
string[] y=new string[number];

for(int i=0;i<number;i++)
{
    y[i] = x[i];
}

Will work fine, however you may need to increment number by one if you want number to be 3 yet store the first 4 values...

Upvotes: 2

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101701

There is no need to for loop. You can do it with LINQ

string[] y = x.Select(item => item).Take(number+1).ToArray();

Upvotes: 2

Related Questions