1

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

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you..i didn't know about Array.Copy method.
2

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...

1 Comment

Thank you Mr.Graham..Now I get it..it wasn't a case of case-sensitivity. I was not using 'i' as an index parameter when accessing y. Silly me...
2

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

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

4 Comments

This is not the most efficient method. However, it has the advantage that you don't need to care about number+1 being bigger then x size.
@Cosmin, OP didn't say anything about that.If that is the case the for loop might be throw exception too.He should check number
Thank you...I will try the solution
That's what I'm saying. By using Take you won't get that exception. You will just get a smaller array so you should no longer be concerned about the check.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.