1

I have a small question.

I have a string array and on the basis of a parameter I need to store the values of the array into a string.

string[] x={"A","B","C","D","F","G"};
for(int i=0;i<number;i++)
{
string y=y+","+x[i];
}

If number=3, then my string should have (A,B,C,D)

The above implementation throws an error that y cannot be used.

What should be the right kind of implementation to achieve the above functionality?

Any help will be greatly appreciated.

Regards

Anurag

3 Answers 3

4

You could try a simple LINQ statement:

var partOfString = string.Join("", x.Take(number));

If you want to pass in 3, but get 4 records, just add 1:

var partOfString = string.Join("", x.Take(number + 1));

If the format you want is literally (A,B,C,D):

var partOfString = string.Format("({0})", string.Join(",", x.Take(number + 1)));
Sign up to request clarification or add additional context in comments.

4 Comments

Let me try..Thank you
He's joining with , and number 3 results in 4 characters, not 3.
No Mr. Grant..I just want the records..no parentheses..I am trying the solutions mentioned here..Spare me some time..Thank you
thank you people..I was able to solve this..It was a small stuff but I was not getting it...:)
1

Modified version of your code.

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

string result = string.Empty;
int number = 3;
for (int i = 0; i < number + 1; i++)
{
     result = result + "," + x[i];
}
result = result.TrimStart(',');

or simple LINQ

string[] x = { "A", "B", "C", "D", "F", "G" };
int number = 3;            
string result = string.Join(",", x.Take(number+1)); ;

Comments

1
string y = String.Empty;
string[] x={"A","B","C","D","F","G"};

for(int i = 0; i < x.GetUpperBound(0); i++)
{
    y = y + "," + x[i];
}
y = y.TrimEnd(',');

And please use the StringBuilder Class for manipulating string.

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.