Reputation: 17298
i try to write a query but my query finished with "Control nvarchar(500), ". i want to finish "Control nvarchar(500)" How can remove ",", " "?
void SqlTable(List listMyColumnNames, string TableName)
{
string Text = "Create table ENG_"+TableName+" (ENG_"+TableName+"_ID integer PRIMARY KEY identity(1,1), ";
char[] MyChar = {',', ' ' };
for (int i = 0; i < listMyColumnNames.Count; )
{
Text+=listMyColumnNames[i]+" nvarchar(500), ";
if (i == listMyColumnNames.Count-1)
Text.TrimEnd(MyChar);
i++;
}
Text+=" )";
Upvotes: 2
Views: 176
Reputation: 5165
Have you thought about using the StringBuilder object to build your string, rather than concatenating yours string in a loop!
http://www.yoda.arachsys.com/csharp/stringbuilder.html
Upvotes: 0
Reputation: 55039
Or you could just remove your Trim call and add `Text = Text.Replace(", )", " )");' at very end.
Upvotes: 0
Reputation: 41519
I think you may want to look at String.Join
. What you can do is transform your column name strings, containing the SQL definition of your colum, e.g. MyColumnName[1]+" nvarchar(500)", into a
listMyColumnDefarray, then
Join` that array with the comma as a separator.
The benefit:
The drawbacks.... none :)
for( String name in listMyColumnNames ) {
listMyColumnDefs.Add( name + " nvarchar(500)" );
}
String mycolumndef = String.Join( listMyColumnDefs, ", ");
Upvotes: 11
Reputation: 383866
There are many ways to fix this, but here's the problem in your code:
if (i == listMyColumnNames.Count-1)
Text.TrimEnd(MyChar); // doesn't work like this!
String
is immutable: you can't invoke a method on it and expect it to be mutated by the method. TrimEnd
instead returns a new String
, so what you need to do is:
Text = Text.TrimEnd(MyChar); // now works fine!
Upvotes: 3
Reputation: 224129
for (int i = 0; i < listMyColumnNames.Count; ++i)
{
Text += listMyColumnNames[i] + " nvarchar(500)";
if (i < listMyColumnNames.Count-1)
Text += ", ";
}
Upvotes: 0