Reputation: 572
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
Upvotes: 1
Views: 62
Reputation: 66449
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)));
Upvotes: 4
Reputation: 2060
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.
Upvotes: 1
Reputation: 32681
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)); ;
Upvotes: 1